休息呼叫Azure



我正试图用我的c#代码登录Azure,并在网上找到了这样的东西。

不确定在这里的作用域数组中传递什么,一旦我获得访问令牌,我如何进行rest调用?

public static string getAccessToken(string[] scopes)
{
var interactiveCredential = new InteractiveBrowserCredential();
return interactiveCredential.GetToken(new Azure.Core.TokenRequestContext(scopes, null)).Token;
}

首先创建一个Azure AD应用程序:

遵循此链接

然后从AD应用程序中获取Tenant ID、Client ID和Client Secret,并使用此类查询您的azure订阅资源。

class CustomLoginCredentials : ServiceClientCredentials
{
//Variables
private static string tenantId = "<Tenant ID goes here>";
private static string clientId = "<Client ID goes here>";
private static string clientSecret = "<Client Secret goes here>";
private static string windowsURL = "https://login.windows.net/";
private static string azureManagementURL = "https://management.azure.com/";

private string AuthenticationToken { get; set; }
public override void InitializeServiceClient<T>(ServiceClient<T> client)
{
var authenticationContext =
new AuthenticationContext(windowsURL + tenantId);
var credential = new ClientCredential(clientId, clientSecret);
var result = authenticationContext.AcquireTokenAsync(azureManagementURL,
clientCredential: credential).Result;
AuthenticationToken = result.AccessToken;
}
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
await base.ProcessHttpRequestAsync(request, cancellationToken);
}
}

示例:

private async void GetAzureResourcesConsumption()
{
var credentials = new CustomLoginCredentials();
ConsumptionManagementClient client = new ConsumptionManagementClient(credentials);
client.SubscriptionId = subscriptionId;
var resources = await client.UsageDetails.ListAsync(null, null, null, top: NumberOfItems);
var results = resources.ToList<UsageDetail>();
} 

你的意思是要获得访问令牌吗?

private static string GetAuthorizationToken()
{
ClientCredential cc = new ClientCredential(ClientId, ServicePrincipalPassword);
var context = new AuthenticationContext("https://login.windows.net/" + AzureTenantId);
var result = context.AcquireTokenAsync("https://management.azure.com/", cc);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
return result.Result.AccessToken;
}

最新更新