如何创建与Microsoft.azure.Management.compute一起使用的serviceclientcredential

use*_*653 13 c# azure

我试图以编程方式从Microsoft.Azure.Management.Compute使用C#检索托管服务.这需要ServiceClientCredential,我不知道如何得到它.谁能帮帮我吗?我可以使用它们,Microsoft.WindowsAzure.Management.Compute但在这里它只返回ResourceManager下的实例而不是经典实例.

Ahm*_*awy 18

首先,您需要创建Active Directory应用程序.使用此链接创建AD应用程序https://azure.microsoft.com/en-us/documentation/articles/resource-group-create-service-principal-portal/

示例代码使用Microsoft.Azure.Management.Compute 13.0.1-prerelease SDK URL:https://www.nuget.org/packages/Microsoft.Azure.Management.Compute/13.0.1-prerelease

public class CustomLoginCredentials : ServiceClientCredentials
    {  
        private string AuthenticationToken { get; set; }
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            var authenticationContext =
                new AuthenticationContext("https://login.windows.net/{tenantID}");
            var credential = new ClientCredential(clientId: "xxxxx-xxxx-xx-xxxx-xxx", clientSecret: "{clientSecret}");

            var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/",
                clientCredential: credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            AuthenticationToken = result.AccessToken;
        }
  public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        if (AuthenticationToken == null)
        {
            throw new InvalidOperationException("Token Provider Cannot Be Null");
        }



        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //request.Version = new Version(apiVersion);
        await base.ProcessHttpRequestAsync(request, cancellationToken);

    }
}
Run Code Online (Sandbox Code Playgroud)

这是如何初始化客户端

 netClient = new Microsoft.Azure.Management.Compute.ComputeManagementClient(new CustomLoginCredentials());

        netClient.SubscriptionId = _subscriptionId;
Run Code Online (Sandbox Code Playgroud)

  • 为什么我们需要在InitializeServiceClient中做这么多?考虑到我们不使用客户端来执行此操作,似乎最好使构造函数能够获取必要的资源并生成令牌提供程序.然后`ProcessHttpRequestAsync`可以从auth上下文中获取新令牌(以确保它是最新的当前令牌) (4认同)