-
Notifications
You must be signed in to change notification settings - Fork 531
/
ServiceCredential.cs
331 lines (278 loc) · 15.3 KB
/
ServiceCredential.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
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
{
/// <summary>
/// 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.
/// <para>
/// <see cref="ServiceAccountCredential"/> inherits from this class in order to support Service Accounts. More
/// details available at: https://developers.google.com/accounts/docs/OAuth2ServiceAccount.
/// <see cref="ComputeCredential"/> 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.
/// </para>
/// <para>
/// <see cref="ExternalAccountCredential"/> 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 <see cref="ExternalAccountCredential"/> inherits from <see cref="ServiceCredential"/>
/// might be construed as misleading. In reality <see cref="ServiceCredential"/> 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 <see cref="ExternalAccountCredential"/> inherits from <see cref="ServiceCredential"/>
/// even when representing a Workforce Identity Federation account.
/// </para>
/// </summary>
public abstract class ServiceCredential : ICredential, ITokenAccessWithHeaders,
IHttpExecuteInterceptor, IHttpUnsuccessfulResponseHandler
{
/// <summary>Logger for this class</summary>
protected static readonly ILogger Logger = ApplicationContext.Logger.ForType<ServiceCredential>();
/// <summary>An initializer class for the service credential. </summary>
public class Initializer
{
/// <summary>Gets the token server URL.</summary>
public string TokenServerUrl { get; private set; }
/// <summary>
/// Gets or sets the clock used to refresh the token when it expires. The default value is
/// <see cref="Google.Apis.Util.SystemClock.Default"/>.
/// </summary>
public IClock Clock { get; set; }
/// <summary>
/// Gets or sets the method for presenting the access token to the resource server.
/// The default value is <see cref="BearerToken.AuthorizationHeaderAccessMethod"/>.
/// </summary>
public IAccessMethod AccessMethod { get; set; }
/// <summary>
/// Gets or sets the factory for creating a <see cref="System.Net.Http.HttpClient"/> instance.
/// </summary>
public IHttpClientFactory HttpClientFactory { get; set; }
/// <summary>
/// Get or sets the exponential back-off policy. Default value is <c>UnsuccessfulResponse503</c>, which
/// means that exponential back-off is used on 503 abnormal HTTP responses.
/// If the value is set to <c>None</c>, no exponential back-off policy is used, and it's up to the user to
/// configure the <see cref="Google.Apis.Http.ConfigurableMessageHandler"/> in an
/// <see cref="Google.Apis.Http.IConfigurableHttpClientInitializer"/> to set a specific back-off
/// implementation (using <see cref="Google.Apis.Http.BackOffHandler"/>).
/// </summary>
public ExponentialBackOffPolicy DefaultExponentialBackOffPolicy { get; set; }
/// <summary>
/// The ID of the project associated to this credential for the purposes of
/// quota calculation and billing. May be null.
/// </summary>
public string QuotaProject { get; set; }
/// <summary>
/// Scopes to request during the authorization grant. May be null or empty.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public IEnumerable<string> Scopes { get; set; }
/// <summary>
/// Initializers to be sent to the <see cref="HttpClientFactory"/> to be set
/// on the <see cref="HttpClient"/> that will be used by the credential to perform
/// token operations.
/// </summary>
internal IList<IConfigurableHttpClientInitializer> HttpClientInitializers { get; }
/// <summary>Constructs a new initializer using the given token server URL.</summary>
public Initializer(string tokenServerUrl)
{
TokenServerUrl = tokenServerUrl;
AccessMethod = new BearerToken.AuthorizationHeaderAccessMethod();
Clock = SystemClock.Default;
DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.UnsuccessfulResponse503;
HttpClientInitializers = new List<IConfigurableHttpClientInitializer>();
}
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<IConfigurableHttpClientInitializer>(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<IConfigurableHttpClientInitializer>(other.HttpClientInitializers);
Scopes = other.Scopes;
}
}
/// <summary>
/// Gets the token server URL.
/// </summary>
/// <remarks>
/// May be null for credential types that resolve token endpoints just before obtaining an access token.
/// This is the case for <see cref="ImpersonatedCredential"/> where the <see cref="ImpersonatedCredential.SourceCredential"/>
/// is a <see cref="ComputeCredential"/>.
/// </remarks>
public string TokenServerUrl { get; }
/// <summary>Gets the clock used to refresh the token if it expires.</summary>
public IClock Clock { get; }
/// <summary>Gets the method for presenting the access token to the resource server.</summary>
public IAccessMethod AccessMethod { get; }
/// <summary>Gets the HTTP client used to make authentication requests to the server.</summary>
public ConfigurableHttpClient HttpClient { get; }
/// <summary>
/// Scopes to request during the authorization grant. May be null or empty.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public IEnumerable<string> Scopes { get; set; }
/// <summary>
/// Returns true if this credential scopes have been explicitly set via this library.
/// Returns false otherwise.
/// </summary>
internal bool HasExplicitScopes => Scopes?.Any() == true;
internal IHttpClientFactory HttpClientFactory { get; }
/// <summary>
/// Initializers to be sent to the <see cref="HttpClientFactory"/> to be set
/// on the <see cref="HttpClient"/> that will be used by the credential to perform
/// token operations.
/// </summary>
internal IEnumerable<IConfigurableHttpClientInitializer> HttpClientInitializers { get; }
internal ExponentialBackOffPolicy DefaultExponentialBackOffPolicy { get; }
private readonly TokenRefreshManager _refreshManager;
/// <summary>Gets the token response which contains the access token.</summary>
public TokenResponse Token
{
get => _refreshManager.Token;
set => _refreshManager.Token = value;
}
/// <summary>
/// The ID of the project associated to this credential for the purposes of
/// quota calculation and billing. May be null.
/// </summary>
public string QuotaProject { get; }
/// <summary>Constructs a new service account credential using the given initializer.</summary>
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<string>();
DefaultExponentialBackOffPolicy = initializer.DefaultExponentialBackOffPolicy;
HttpClientInitializers = new List<IConfigurableHttpClientInitializer>(initializer.HttpClientInitializers).AsReadOnly();
HttpClientFactory = initializer.HttpClientFactory ?? new HttpClientFactory();
HttpClient = HttpClientFactory.CreateHttpClient(BuildCreateHttpClientArgs());
_refreshManager = new TokenRefreshManager(RequestAccessTokenAsync, Clock, Logger);
QuotaProject = initializer.QuotaProject;
}
/// <summary>
/// Builds HTTP client creation args from this credential settings.
/// </summary>
protected internal CreateHttpClientArgs BuildCreateHttpClientArgs()
{
var httpArgs = new CreateHttpClientArgs();
// Add exponential back-off initializer if necessary.
if (DefaultExponentialBackOffPolicy != ExponentialBackOffPolicy.None)
{
httpArgs.Initializers.Add(
new ExponentialBackOffInitializer(DefaultExponentialBackOffPolicy,
() => new BackOffHandler(new ExponentialBackOff())));
}
// Add other initializers
foreach (var httpClientInitializer in HttpClientInitializers)
{
httpArgs.Initializers.Add(httpClientInitializer);
}
return httpArgs;
}
#region IConfigurableHttpClientInitializer
/// <inheritdoc/>
public void Initialize(ConfigurableHttpClient httpClient) =>
httpClient.MessageHandler.Credential = this;
#endregion
#region IHttpExecuteInterceptor implementation
/// <inheritdoc/>
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
/// <summary>
/// Decorates unsuccessful responses, returns true if the response gets modified.
/// See IHttpUnsuccessfulResponseHandler for more information.
/// </summary>
public async Task<bool> 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
/// <summary>
/// Gets an access token to authorize a request. If the existing token expires soon, try to refresh it first.
/// <seealso cref="ITokenAccess.GetAccessTokenForRequestAsync"/>
/// </summary>
public virtual Task<string> GetAccessTokenForRequestAsync(string authUri = null,
CancellationToken cancellationToken = default(CancellationToken)) =>
_refreshManager.GetAccessTokenForRequestAsync(cancellationToken);
#endregion
#region ITokenAccessWithHeaders implementation
/// <inheritdoc />
public async Task<AccessTokenWithHeaders> GetAccessTokenWithHeadersForRequestAsync(string authUri = null, CancellationToken cancellationToken = default)
{
string token = await GetAccessTokenForRequestAsync(authUri, cancellationToken).ConfigureAwait(false);
return new AccessTokenWithHeaders.Builder { QuotaProject = QuotaProject }.Build(token);
}
#endregion
/// <summary>Requests a new token.</summary>
/// <param name="taskCancellationToken">Cancellation token to cancel operation.</param>
/// <returns><c>true</c> if a new token was received successfully.</returns>
public abstract Task<bool> RequestAccessTokenAsync(CancellationToken taskCancellationToken);
}
}