/*
Copyright 2014 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Http;
using Google.Apis.Logging;
using Google.Apis.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Apis.Auth.OAuth2
{
///
/// This type of Google OAuth 2.0 credential enables access to protected resources using an access token when
/// interacting server to server. For example, a service account credential could be used to access Google Cloud
/// Storage from a web application without a user's involvement.
///
/// inherits from this class in order to support Service Accounts. More
/// details available at: https://developers.google.com/accounts/docs/OAuth2ServiceAccount.
/// is another example of a class that inherits from this
/// class in order to support Compute credentials. For more information about Compute authentication, see:
/// https://cloud.google.com/compute/docs/authentication.
///
///
/// inherits from this class to support both Workload Identity Federation
/// and Workforce Identity Federation. You can read more about these topics in
/// https://cloud.google.com/iam/docs/workload-identity-federation and
/// https://cloud.google.com/iam/docs/workforce-identity-federation respectively.
/// Note that in the case of Workforce Identity Federation, the external account does not represent a service account
/// but a user account, so, the fact that inherits from
/// might be construed as misleading. In reality is not tied to a service account
/// in terms of implementation, only in terms of name. For instance, a better name for this class might have been NoUserFlowCredential, and
/// in that sense, it's correct that inherits from
/// even when representing a Workforce Identity Federation account.
///
///
public abstract class ServiceCredential : ICredential, ITokenAccessWithHeaders,
IHttpExecuteInterceptor, IHttpUnsuccessfulResponseHandler
{
/// Logger for this class
protected static readonly ILogger Logger = ApplicationContext.Logger.ForType();
/// An initializer class for the service credential.
public class Initializer
{
/// Gets the token server URL.
public string TokenServerUrl { get; private set; }
///
/// Gets or sets the clock used to refresh the token when it expires. The default value is
/// .
///
public IClock Clock { get; set; }
///
/// Gets or sets the method for presenting the access token to the resource server.
/// The default value is .
///
public IAccessMethod AccessMethod { get; set; }
///
/// Gets or sets the factory for creating a instance.
///
public IHttpClientFactory HttpClientFactory { get; set; }
///
/// Indicates which of exceptions and / or HTTP status codes are automatically retried using exponential backoff.
/// The default value is which means retries will be
/// executed as recommended by each service. For services that have no specific recommendations
/// will be used, which means HTTP Status code 503
/// will be retried with exponential backoff.
/// If set to no automatic retries will happen.
/// Calling code may still specify custom retries by configuring .
///
public ExponentialBackOffPolicy DefaultExponentialBackOffPolicy { get; set; }
///
/// The ID of the project associated to this credential for the purposes of
/// quota calculation and billing. May be null.
///
public string QuotaProject { get; set; }
///
/// Scopes to request during the authorization grant. May be null or empty.
///
///
/// If the scopes are pre-granted through the environement, like in GCE where scopes are granted to the VM,
/// scopes set here will be ignored.
///
public IEnumerable Scopes { get; set; }
///
/// Initializers to be sent to the to be set
/// on the that will be used by the credential to perform
/// token operations.
///
internal IList HttpClientInitializers { get; }
/// Constructs a new initializer using the given token server URL.
public Initializer(string tokenServerUrl)
{
TokenServerUrl = tokenServerUrl;
AccessMethod = new BearerToken.AuthorizationHeaderAccessMethod();
Clock = SystemClock.Default;
DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.RecommendedOrDefault;
HttpClientInitializers = new List();
}
internal Initializer(ServiceCredential other)
{
TokenServerUrl = other.TokenServerUrl;
Clock = other.Clock;
AccessMethod = other.AccessMethod;
HttpClientFactory = other.HttpClientFactory;
DefaultExponentialBackOffPolicy = other.DefaultExponentialBackOffPolicy;
QuotaProject = other.QuotaProject;
HttpClientInitializers = new List(other.HttpClientInitializers);
Scopes = other.Scopes;
}
internal Initializer(Initializer other)
{
TokenServerUrl = other.TokenServerUrl;
Clock = other.Clock;
AccessMethod = other.AccessMethod;
HttpClientFactory = other.HttpClientFactory;
DefaultExponentialBackOffPolicy = other.DefaultExponentialBackOffPolicy;
QuotaProject = other.QuotaProject;
HttpClientInitializers = new List(other.HttpClientInitializers);
Scopes = other.Scopes;
}
}
///
/// Gets the token server URL.
///
///
/// May be null for credential types that resolve token endpoints just before obtaining an access token.
/// This is the case for where the
/// is a .
///
public string TokenServerUrl { get; }
/// Gets the clock used to refresh the token if it expires.
public IClock Clock { get; }
/// Gets the method for presenting the access token to the resource server.
public IAccessMethod AccessMethod { get; }
/// Gets the HTTP client used to make authentication requests to the server.
public ConfigurableHttpClient HttpClient { get; }
///
/// Scopes to request during the authorization grant. May be null or empty.
///
///
/// If the scopes are pre-granted through the environment, like in GCE where scopes are granted to the VM,
/// scopes set here will be ignored.
///
public IEnumerable Scopes { get; set; }
///
/// Returns true if this credential scopes have been explicitly set via this library.
/// Returns false otherwise.
///
internal bool HasExplicitScopes => Scopes?.Any() == true;
internal IHttpClientFactory HttpClientFactory { get; }
///
/// Initializers to be sent to the to be set
/// on the that will be used by the credential to perform
/// token operations.
///
internal IEnumerable HttpClientInitializers { get; }
internal ExponentialBackOffPolicy DefaultExponentialBackOffPolicy { get; }
private readonly TokenRefreshManager _refreshManager;
/// Gets the token response which contains the access token.
public TokenResponse Token
{
get => _refreshManager.Token;
set => _refreshManager.Token = value;
}
///
/// The ID of the project associated to this credential for the purposes of
/// quota calculation and billing. May be null.
///
public string QuotaProject { get; }
/// Constructs a new service account credential using the given initializer.
public ServiceCredential(Initializer initializer)
{
TokenServerUrl = initializer.TokenServerUrl;
AccessMethod = initializer.AccessMethod.ThrowIfNull("initializer.AccessMethod");
Clock = initializer.Clock.ThrowIfNull("initializer.Clock");
Scopes = initializer.Scopes?.Where(scope => !string.IsNullOrWhiteSpace(scope)).ToList().AsReadOnly()
?? Enumerable.Empty();
DefaultExponentialBackOffPolicy = initializer.DefaultExponentialBackOffPolicy;
HttpClientInitializers = new List(initializer.HttpClientInitializers).AsReadOnly();
HttpClientFactory = initializer.HttpClientFactory ?? new HttpClientFactory();
HttpClient = HttpClientFactory.CreateHttpClient(BuildCreateHttpClientArgs());
_refreshManager = new TokenRefreshManager(RequestAccessTokenAsync, Clock, Logger);
QuotaProject = initializer.QuotaProject;
}
///
/// Builds HTTP client creation args from all this credential settings.
/// These are used for initializing .
///
protected internal CreateHttpClientArgs BuildCreateHttpClientArgs()
{
var args = BuildCreateHttpClientArgsWithNoRetries();
AddHttpClientRetryConfiguration(args);
return args;
}
///
/// Builds HTTP client creation args from this credential settings except for .
///
private protected CreateHttpClientArgs BuildCreateHttpClientArgsWithNoRetries()
{
var httpArgs = new CreateHttpClientArgs();
// Add initializers
foreach (var httpClientInitializer in HttpClientInitializers)
{
httpArgs.Initializers.Add(httpClientInitializer);
}
return httpArgs;
}
///
/// Configures with the expected retry policy for based on
/// . Can be extended as different credentials use different token
/// endpoints that may recommende different retry strategies.
///
private protected virtual void AddHttpClientRetryConfiguration(CreateHttpClientArgs args)
{
// Add exponential back-off initializer if necessary.
if (DefaultExponentialBackOffPolicy != ExponentialBackOffPolicy.None)
{
var effectiveRetryPolicy = DefaultExponentialBackOffPolicy.HasFlag(ExponentialBackOffPolicy.RecommendedOrDefault) ?
// At this level there's no recommendation, but we know default is retry 503.
// Remove RecommendedOrDefault and add UnsuccessfulResponse503.
(DefaultExponentialBackOffPolicy & ~ExponentialBackOffPolicy.RecommendedOrDefault) | ExponentialBackOffPolicy.UnsuccessfulResponse503 :
DefaultExponentialBackOffPolicy;
args.Initializers.Add(new ExponentialBackOffInitializer(effectiveRetryPolicy, () => new BackOffHandler(new ExponentialBackOff())));
}
}
///
/// Configures with the expected retry policy for an HttpClient that's used only with the IAM SignBlob endpoint, based on
/// .
///
private protected void AddIamSignBlobRetryConfiguration(CreateHttpClientArgs args)
{
// In case the user explicitly configured retry policy.
var customRetryPolicy = GoogleAuthConsts.StripIamSignBlobEndpointRecommendedPolicy(DefaultExponentialBackOffPolicy);
if (customRetryPolicy != ExponentialBackOffPolicy.None)
{
args.Initializers.Add(new ExponentialBackOffInitializer(customRetryPolicy, () => new BackOffHandler(new ExponentialBackOff())));
}
// In case recommended is also configured.
if (DefaultExponentialBackOffPolicy.HasFlag(ExponentialBackOffPolicy.RecommendedOrDefault))
{
args.Initializers.Add(GoogleAuthConsts.IamSignBlobEndpointRecommendedRetry);
}
}
#region IConfigurableHttpClientInitializer
///
public void Initialize(ConfigurableHttpClient httpClient) =>
httpClient.MessageHandler.Credential = this;
#endregion
#region IHttpExecuteInterceptor implementation
///
public async Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var audience = new UriBuilder(request.RequestUri) { Query = string.Empty, Path = string.Empty }.Uri.ToString();
var accessToken = await GetAccessTokenWithHeadersForRequestAsync(audience, cancellationToken).ConfigureAwait(false);
AccessMethod.Intercept(request, accessToken.AccessToken);
accessToken.AddHeaders(request);
}
#endregion
#region IHttpUnsuccessfulResponseHandler
///
/// Decorates unsuccessful responses, returns true if the response gets modified.
/// See IHttpUnsuccessfulResponseHandler for more information.
///
public async Task HandleResponseAsync(HandleUnsuccessfulResponseArgs args)
{
// If the response was unauthorized, request a new access token so that the original
// request can be retried.
// TODO(peleyal): check WWW-Authenticate header.
if (args.Response.StatusCode == HttpStatusCode.Unauthorized)
{
bool tokensEqual = false;
if (Token != null)
{
tokensEqual = Object.Equals(
Token.AccessToken, AccessMethod.GetAccessToken(args.Request));
}
return !tokensEqual
|| await RequestAccessTokenAsync(args.CancellationToken).ConfigureAwait(false);
}
return false;
}
#endregion
#region ITokenAccess implementation
///
/// Gets an access token to authorize a request. If the existing token expires soon, try to refresh it first.
///
///
public virtual Task GetAccessTokenForRequestAsync(string authUri = null,
CancellationToken cancellationToken = default(CancellationToken)) =>
_refreshManager.GetAccessTokenForRequestAsync(cancellationToken);
#endregion
#region ITokenAccessWithHeaders implementation
///
public async Task GetAccessTokenWithHeadersForRequestAsync(string authUri = null, CancellationToken cancellationToken = default)
{
string token = await GetAccessTokenForRequestAsync(authUri, cancellationToken).ConfigureAwait(false);
return new AccessTokenWithHeaders.Builder { QuotaProject = QuotaProject }.Build(token);
}
#endregion
/// Requests a new token.
/// Cancellation token to cancel operation.
/// true if a new token was received successfully.
public abstract Task RequestAccessTokenAsync(CancellationToken taskCancellationToken);
}
}