2016-05-30 1 views
0

Я пытаюсь подключиться к моей лазурной подписке, у меня есть код, который позволит мне получить токенКак подключиться к лазурной подписке, используя токен подключения?

  var authContext = new AuthenticationContext(string.Format 
      ("https://login.windows.net/{0}", tenantId)); 
      var credential = new ClientCredential(applicationId, password); 
      AuthenticationResult token = authContext.AcquireTokenAsync 
       ("https://management.core.windows.net/", credential).Result; 

      if (token == null) 
      { 
       Console.WriteLine("Failed to obtain the token"); 
       return; 
      } 

от этого шага я не знаю, как использовать ResourceManagementClient класс для подключения ...

ответ

5

После того, как вы получили маркер, вы можете использовать его как это с «ResourceManagementClient»:

string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length); 

    Microsoft.Rest.ServiceClientCredentials credentials = new TokenCredentials(token); 

    using (var rgClient = new ResourceManagementClient(credentials)) 
    { 
     rgClient.SubscriptionId = "xxxxxxx-xxxxx-xxxxxxxx-xxxxxxx"; 
     var rgs = rgClient.ResourceGroups.List(); 
    }; 

вы можете создать свой собственный «TokenCredentials» класс, который наследует от «ServiceClientCredentials», как это:

public class TokenCredentials : ServiceClientCredentials 
{ 

    /// <summary> 
    /// The bearer token type, as serialized in an http Authentication header. 
    /// </summary> 
    private const string BearerTokenType = "Bearer"; 

    /// <summary> 
    /// Gets or sets secure token used to authenticate against Microsoft Azure API. 
    /// No anonymous requests are allowed. 
    /// </summary> 
    protected ITokenProvider TokenProvider { get; private set; } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="TokenCredentials"/> 
    /// class with the given 'Bearer' token. 
    /// </summary> 
    /// <param name="token">Valid JSON Web Token (JWT).</param> 
    public TokenCredentials(string token) 
     : this(token, BearerTokenType) 
    { 
    } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="TokenCredentials"/> 
    /// class with the given token and token type. 
    /// </summary> 
    /// <param name="token">Valid JSON Web Token (JWT).</param> 
    /// <param name="tokenType">The token type of the given token.</param> 
    public TokenCredentials(string token, string tokenType) 
     : this(new StringTokenProvider(token, tokenType)) 
    { 
     if (string.IsNullOrEmpty(token)) 
     { 
      throw new ArgumentNullException("token"); 
     } 
     if (string.IsNullOrEmpty(tokenType)) 
     { 
      throw new ArgumentNullException("tokenType"); 
     } 
    } 

    /// <summary> 
    /// Create an access token credentials object, given an interface to a token source. 
    /// </summary> 
    /// <param name="tokenProvider">The source of tokens for these credentials.</param> 
    public TokenCredentials(ITokenProvider tokenProvider) 
    { 
     if (tokenProvider == null) 
     { 
      throw new ArgumentNullException("tokenProvider"); 
     } 

     this.TokenProvider = tokenProvider; 
    } 

    /// <summary> 
    /// Apply the credentials to the HTTP request. 
    /// </summary> 
    /// <param name="request">The HTTP request.</param> 
    /// <param name="cancellationToken">Cancellation token.</param> 
    /// <returns> 
    /// Task that will complete when processing has completed. 
    /// </returns> 
    public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, 
     CancellationToken cancellationToken) 
    { 
     if (request == null) 
     { 
      throw new ArgumentNullException("request"); 
     } 

     if (TokenProvider == null) 
     { 
      throw new ArgumentNullException("Token provider"); 
     } 

     request.Headers.Authorization = await TokenProvider.GetAuthenticationHeaderAsync(cancellationToken); 
     await base.ProcessHttpRequestAsync(request, cancellationToken); 
    } 
} 
+0

привет сэр, я думаю, что у меня есть опорный problème Не удается преобразовать из Microsoft.Rest.TokenCredentials в Microsoft.Azure.SubscriptionCloudCredentials я судимый найти его в Nu получить, но ... п.с. : le monde est Petit Thibaut, c'est maroine, on s'est vu dans l'azure boot camp avec Maxime ^^ –

+0

Вы можете создать свой собственный класс «TokenCredentials»! Я только что редактировал сообщение! –

+0

спасибо за помощь! –

Смежные вопросы