// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Net.Http; namespace k8s.Authentication { /// /// Token based credentials for use with a REST Service Client. /// public class TokenCredentials : ServiceClientCredentials { /// /// The bearer token type, as serialized in an http Authentication header. /// private const string BearerTokenType = "Bearer"; /// /// Gets secure token used to authenticate against Microsoft Azure API. /// No anonymous requests are allowed. /// protected ITokenProvider TokenProvider { get; private set; } /// /// Gets Tenant ID /// public string TenantId { get; private set; } /// /// Gets UserInfo.DisplayableId /// public string CallerId { get; private set; } /// /// Initializes a new instance of the /// class with the given 'Bearer' token. /// /// Valid JSON Web Token (JWT). public TokenCredentials(string token) : this(token, BearerTokenType) { } /// /// Initializes a new instance of the /// class with the given token and token type. /// /// Valid JSON Web Token (JWT). /// The token type of the given token. 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"); } } /// /// Initializes a new instance of the class. /// Create an access token credentials object, given an interface to a token source. /// /// The source of tokens for these credentials. public TokenCredentials(ITokenProvider tokenProvider) { if (tokenProvider == null) { throw new ArgumentNullException("tokenProvider"); } TokenProvider = tokenProvider; } /// /// Initializes a new instance of the class. /// Create an access token credentials object, given an interface to a token source. /// /// The source of tokens for these credentials. /// Tenant ID from AuthenticationResult /// UserInfo.DisplayableId field from AuthenticationResult public TokenCredentials(ITokenProvider tokenProvider, string tenantId, string callerId) : this(tokenProvider) { TenantId = tenantId; CallerId = callerId; } /// /// Apply the credentials to the HTTP request. /// /// The HTTP request. /// Cancellation token. /// /// Task that will complete when processing has completed. /// public override async Task ProcessHttpRequestAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (TokenProvider == null) { throw new ArgumentNullException(nameof(TokenProvider)); } request.Headers.Authorization = await TokenProvider.GetAuthenticationHeaderAsync(cancellationToken).ConfigureAwait(false); await base.ProcessHttpRequestAsync(request, cancellationToken).ConfigureAwait(false); } } }