File size: 22,528 Bytes
7b715bc | 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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | /*
Copyright 2013 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;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Http;
using Google.Apis.Json;
using Google.Apis.Tests.Mocks;
using Google.Apis.Util;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Google.Apis.Auth.Tests.OAuth2.Flows
{
/// <summary>Tests for <see cref="Google.Apis.Auth.OAuth2.AuthorizationCodeFlow"/>.</summary>
public class AuthorizationCodeFlowTests
{
private const string TokenUrl = "https://token.com";
private const string AuthorizationCodeUrl = "https://authorization.com";
#region Constructor
[Fact]
public void TestConstructor_ArgumentException()
{
var initializer = new AuthorizationCodeFlow.Initializer("https://authorization_code.com", "https://token.com");
// ClientSecrets are missing.
var exception = Assert.Throws<ArgumentException>(() => new AuthorizationCodeFlow(initializer));
Assert.Contains("You MUST set ClientSecret or ClientSecretStream", exception.Message);
}
[Fact]
public void TestConstructor_DefaultValues()
{
var flow = CreateFlow();
Assert.NotNull(flow.AccessMethod);
Assert.IsType<BearerToken.AuthorizationHeaderAccessMethod>(flow.AccessMethod);
Assert.Equal("https://authorization.com", flow.AuthorizationServerUrl);
Assert.NotNull(flow.ClientSecrets);
Assert.Equal("id", flow.ClientSecrets.ClientId);
Assert.Equal("secret", flow.ClientSecrets.ClientSecret);
Assert.IsType<SystemClock>(flow.Clock);
Assert.Null(flow.DataStore);
Assert.NotNull(flow.HttpClient);
Assert.Null(flow.Scopes);
Assert.Equal("https://token.com", flow.TokenServerUrl);
// Disable "<member> is obsolete" warning for these uses.
// MessageHandler no longer provides a supported way for clients to query the list of handlers,
// but we rely on the obsolete property as an implementation detail here.
#pragma warning disable 618
IHttpUnsuccessfulResponseHandler badResponseHandler = Assert.Single(flow.HttpClient.MessageHandler.UnsuccessfulResponseHandlers);
IHttpExceptionHandler exceptionHandler = Assert.Single(flow.HttpClient.MessageHandler.ExceptionHandlers);
#pragma warning restore 618
BackOffHandler backOffBadResponseHandler = Assert.IsType<BackOffHandler>(badResponseHandler);
BackOffHandler backOffExceptionHandler = Assert.IsType<BackOffHandler>(exceptionHandler);
Assert.Same(backOffBadResponseHandler, backOffExceptionHandler);
}
#endregion
[Fact]
public void WithHttpClientFactory()
{
var flow = CreateFlow();
var factory = new HttpClientFactory();
var flowWithFactory = Assert.IsType<AuthorizationCodeFlow>(
((IHttpAuthorizationFlow)flow).WithHttpClientFactory(factory));
Assert.NotSame(flow, flowWithFactory);
Assert.NotSame(flow.HttpClient, flowWithFactory.HttpClient);
Assert.NotSame(flow.HttpClientFactory, flowWithFactory.HttpClientFactory);
Assert.Same(factory, flowWithFactory.HttpClientFactory);
}
[Fact]
public void Deafault_RecommendedRetryPolicy()
{
var mockFactory = new MockHttpClientFactory(new FetchesTokenMessageHandler());
var flow = CreateFlow(httpClientFactory: mockFactory);
var args = Assert.Single(mockFactory.AllCreateHttpClientArgs);
var retryInitializer = Assert.Single(args.Initializers);
Assert.Same(GoogleAuthConsts.OAuth2TokenEndpointRecommendedRetry, retryInitializer);
}
[Fact]
public void BadResponse503AndRecommended_RecommendedRetryPolicy()
{
var mockFactory = new MockHttpClientFactory(new FetchesTokenMessageHandler());
var flow = CreateFlow(
httpClientFactory: mockFactory,
exponentialBackOffPolicy: ExponentialBackOffPolicy.UnsuccessfulResponse503 | ExponentialBackOffPolicy.RecommendedOrDefault);
var args = Assert.Single(mockFactory.AllCreateHttpClientArgs);
var retryInitializer = Assert.Single(args.Initializers);
Assert.Same(GoogleAuthConsts.OAuth2TokenEndpointRecommendedRetry, retryInitializer);
}
[Fact]
public void ExceptionAndRecommended_RecommendedAndOtherRetryPolicy()
{
var mockFactory = new MockHttpClientFactory(new FetchesTokenMessageHandler());
var flow = CreateFlow(
httpClientFactory: mockFactory,
exponentialBackOffPolicy: ExponentialBackOffPolicy.Exception | ExponentialBackOffPolicy.RecommendedOrDefault);
var args = Assert.Single(mockFactory.AllCreateHttpClientArgs);
Assert.Equal(2, args.Initializers.Count);
Assert.Contains(GoogleAuthConsts.OAuth2TokenEndpointRecommendedRetry, args.Initializers);
Assert.Contains(args.Initializers, initializer => initializer != GoogleAuthConsts.OAuth2TokenEndpointRecommendedRetry);
}
[Fact]
public void NoRetryPolicy()
{
var mockFactory = new MockHttpClientFactory(new FetchesTokenMessageHandler());
var flow = CreateFlow(httpClientFactory: mockFactory, exponentialBackOffPolicy: ExponentialBackOffPolicy.None);
var args = Assert.Single(mockFactory.AllCreateHttpClientArgs);
Assert.Empty(args.Initializers);
}
[Theory]
[InlineData(ExponentialBackOffPolicy.Exception)]
[InlineData(ExponentialBackOffPolicy.UnsuccessfulResponse503)]
[InlineData(ExponentialBackOffPolicy.Exception | ExponentialBackOffPolicy.UnsuccessfulResponse503)]
public void OtherThanRecommendedRetryPolicy(ExponentialBackOffPolicy policy)
{
var mockFactory = new MockHttpClientFactory(new FetchesTokenMessageHandler());
var flow = CreateFlow(httpClientFactory: mockFactory, exponentialBackOffPolicy: policy);
var args = Assert.Single(mockFactory.AllCreateHttpClientArgs);
var retryInitializer = Assert.Single(args.Initializers);
Assert.NotSame(GoogleAuthConsts.OAuth2TokenEndpointRecommendedRetry, retryInitializer);
}
#region LoadToken
[Fact]
public async Task LoadTokenAsync_NoDataStore()
{
var flow = CreateFlow();
Assert.Null(await flow.LoadTokenAsync("user", default));
}
[Fact]
public async Task LoadTokenAsync_NullResponse()
{
Assert.Null(await SubtestLoadTokenAsync(null));
}
[Fact]
public async Task LoadTokenAsync_TokenResponse()
{
TokenResponse response = new TokenResponse
{
AccessToken = "access"
};
var result = await SubtestLoadTokenAsync(response);
Assert.Equal(response, result);
}
private async Task<TokenResponse> SubtestLoadTokenAsync(TokenResponse response)
{
var store = new FakeDataStore { TokenResponse = response };
var flow = CreateFlow(dataStore: store);
var result = await flow.LoadTokenAsync("user", default);
Assert.Equal("user", store.FetchedKey);
return result;
}
#endregion
#region CreateAuthorizationCodeRequest
[Fact]
public void TestCreateAuthorizationCodeRequest()
{
var request = CreateFlow(scopes: new[] { "a", "b" }).CreateAuthorizationCodeRequest("redirect");
Assert.Equal(new Uri(AuthorizationCodeUrl), request.AuthorizationServerUrl);
Assert.Equal("id", request.ClientId);
Assert.Equal("redirect", request.RedirectUri);
Assert.Equal("code", request.ResponseType);
Assert.Equal("a b", request.Scope);
Assert.Null(request.State);
}
[Fact]
public void TestCreateAuthorizationCodeRequest_DefaultValues()
{
var request = CreateFlow().CreateAuthorizationCodeRequest("redirect");
Assert.Equal(new Uri(AuthorizationCodeUrl), request.AuthorizationServerUrl);
Assert.Equal("id", request.ClientId);
Assert.Equal("redirect", request.RedirectUri);
Assert.Equal("code", request.ResponseType);
Assert.Null(request.Scope);
Assert.Null(request.State);
}
#endregion
[Fact]
public async Task TestExchangeCodeForTokenAsync()
{
var store = new FakeDataStore();
var handler = new FetchTokenMessageHandler();
handler.AuthorizationCodeTokenRequest = new AuthorizationCodeTokenRequest()
{
Code = "c0de",
RedirectUri = "redIrect",
Scope = "a"
};
MockHttpClientFactory mockFactory = new MockHttpClientFactory(handler);
var flow = CreateFlow(httpClientFactory: mockFactory, scopes: new[] { "a" }, dataStore: store);
var response = await flow.ExchangeCodeForTokenAsync("uSer", "c0de", "redIrect", default);
SubtestTokenResponse(response);
Assert.Equal("uSer", store.StoredKey);
}
[Fact]
public async Task TestExchangeCodeForTokenAsync_NullScopes()
{
var store = new FakeDataStore();
var handler = new FetchTokenMessageHandler();
handler.AuthorizationCodeTokenRequest = new AuthorizationCodeTokenRequest()
{
Code = "c0de",
RedirectUri = "redIrect",
Scope = null
};
MockHttpClientFactory mockFactory = new MockHttpClientFactory(handler);
var flow = CreateFlow(httpClientFactory: mockFactory, scopes: null, dataStore: store);
var response = await flow.ExchangeCodeForTokenAsync("uSer", "c0de", "redIrect", default);
SubtestTokenResponse(response);
Assert.Equal("uSer", store.StoredKey);
}
[Fact]
public async Task TestRefreshTokenAsync()
{
var store = new FakeDataStore();
var handler = new FetchTokenMessageHandler();
handler.RefreshTokenRequest = new RefreshTokenRequest()
{
RefreshToken = "REFRESH",
Scope = "a"
};
MockHttpClientFactory mockFactory = new MockHttpClientFactory(handler);
var flow = CreateFlow(httpClientFactory: mockFactory, scopes: new[] { "a" }, dataStore: store);
var response = await flow.RefreshTokenAsync("uSer", "REFRESH", default);
SubtestTokenResponse(response);
Assert.Equal("uSer", store.StoredKey);
}
#region FetchToken
/// <summary>
/// Fetch token message handler, which expects an authorization code token request or a refresh token request.
/// It verifies all the query parameters are valid and return an error response in case <see cref="Error"/>
/// is <c>true</c>.
/// </summary>
public class FetchTokenMessageHandler : CountableMessageHandler
{
internal AuthorizationCodeTokenRequest AuthorizationCodeTokenRequest { get; set; }
internal RefreshTokenRequest RefreshTokenRequest { get; set; }
internal bool Error { get; set; }
protected override async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken taskCancellationToken)
{
Assert.Equal(new Uri(TokenUrl), request.RequestUri);
if (AuthorizationCodeTokenRequest != null)
{
// Verify right parameters.
var content = await request.Content.ReadAsStringAsync();
foreach (var parameter in content.Split('&'))
{
var keyValue = parameter.Split('=');
switch (keyValue[0])
{
case "code":
Assert.Equal("c0de", keyValue[1]);
break;
case "redirect_uri":
Assert.Equal("redIrect", keyValue[1]);
break;
case "scope":
Assert.Equal("a", keyValue[1]);
break;
case "grant_type":
Assert.Equal("authorization_code", keyValue[1]);
break;
case "client_id":
Assert.Equal("id", keyValue[1]);
break;
case "client_secret":
Assert.Equal("secret", keyValue[1]);
break;
default:
throw new ArgumentOutOfRangeException("Invalid parameter!");
}
}
}
else
{
// Verify right parameters.
var content = await request.Content.ReadAsStringAsync();
foreach (var parameter in content.Split('&'))
{
var keyValue = parameter.Split('=');
switch (keyValue[0])
{
case "refresh_token":
Assert.Equal("REFRESH", keyValue[1]);
break;
case "scope":
Assert.Equal("a", keyValue[1]);
break;
case "grant_type":
Assert.Equal("refresh_token", keyValue[1]);
break;
case "client_id":
Assert.Equal("id", keyValue[1]);
break;
case "client_secret":
Assert.Equal("secret", keyValue[1]);
break;
default:
throw new ArgumentOutOfRangeException("Invalid parameter!");
}
}
}
var response = new HttpResponseMessage();
if (Error)
{
response.StatusCode = System.Net.HttpStatusCode.BadRequest;
var serializedObject = NewtonsoftJsonSerializer.Instance.Serialize(new TokenErrorResponse
{
Error = "error",
ErrorDescription = "desc",
ErrorUri = "uri"
});
response.Content = new StringContent(serializedObject, Encoding.UTF8);
}
else
{
var serializedObject = NewtonsoftJsonSerializer.Instance.Serialize(new TokenResponse
{
AccessToken = "a",
RefreshToken = "r",
ExpiresInSeconds = 100,
Scope = "b",
});
response.Content = new StringContent(serializedObject, Encoding.UTF8);
}
return response;
}
}
[Fact]
public async Task TestFetchTokenAsync_AuthorizationCodeRequest()
{
var handler = new FetchTokenMessageHandler();
handler.AuthorizationCodeTokenRequest = new AuthorizationCodeTokenRequest()
{
Code = "c0de",
RedirectUri = "redIrect",
Scope = "a"
};
MockHttpClientFactory mockFactory = new MockHttpClientFactory(handler);
var flow = CreateFlow(httpClientFactory: mockFactory);
var response = await flow.FetchTokenAsync("user", handler.AuthorizationCodeTokenRequest, default);
SubtestTokenResponse(response);
}
[Fact]
public async Task TestFetchTokenAsync_RefreshTokenRequest()
{
var handler = new FetchTokenMessageHandler();
handler.RefreshTokenRequest = new RefreshTokenRequest()
{
RefreshToken = "REFRESH",
Scope = "a"
};
MockHttpClientFactory mockFactory = new MockHttpClientFactory(handler);
var flow = CreateFlow(httpClientFactory: mockFactory);
var response = await flow.FetchTokenAsync("user", handler.RefreshTokenRequest, default);
SubtestTokenResponse(response);
}
[Fact]
public async Task TestFetchTokenAsync_AuthorizationCodeRequest_Error()
{
var handler = new FetchTokenMessageHandler();
handler.AuthorizationCodeTokenRequest = new AuthorizationCodeTokenRequest()
{
Code = "c0de",
RedirectUri = "redIrect",
Scope = "a"
};
handler.Error = true;
await SubtestFetchTokenAsync_Error(handler);
}
[Fact]
public async Task TestFetchTokenAsync_RefreshTokenRequest_Error()
{
var handler = new FetchTokenMessageHandler();
handler.RefreshTokenRequest = new RefreshTokenRequest()
{
RefreshToken = "REFRESH",
Scope = "a"
};
handler.Error = true;
await SubtestFetchTokenAsync_Error(handler);
}
// TODO: Potentially rewrite these as a Theory with TheoryData. (Hard to do inline.)
/// <summary>Subtest for receiving an error token response.</summary>
/// <param name="handler">The message handler.</param>
private async Task SubtestFetchTokenAsync_Error(FetchTokenMessageHandler handler)
{
MockHttpClientFactory mockFactory = new MockHttpClientFactory(handler);
var flow = CreateFlow(httpClientFactory: mockFactory);
var request = (TokenRequest) handler.AuthorizationCodeTokenRequest ?? handler.RefreshTokenRequest;
var exception = await Assert.ThrowsAsync<TokenResponseException>(() => flow.FetchTokenAsync("user", request, default));
var error = exception.Error;
Assert.Equal("error", error.Error);
Assert.Equal("desc", error.ErrorDescription);
Assert.Equal("uri", error.ErrorUri);
}
#endregion
/// <summary>Creates an authorization code flow with the given parameters.</summary>
/// <param name="dataStore">The data store.</param>
/// <param name="scopes">The Scopes.</param>
/// <param name="httpClientFactory">The HTTP client factory. If not set the default will be used.</param>
/// <returns>Authorization code flow</returns>
private AuthorizationCodeFlow CreateFlow(
IDataStore dataStore = null,
IEnumerable<string> scopes = null,
IHttpClientFactory httpClientFactory = null,
ExponentialBackOffPolicy? exponentialBackOffPolicy = null)
{
var secrets = new ClientSecrets() { ClientId = "id", ClientSecret = "secret" };
var initializer = new AuthorizationCodeFlow.Initializer(AuthorizationCodeUrl, TokenUrl)
{
ClientSecrets = secrets,
HttpClientFactory = httpClientFactory
};
if (dataStore != null)
{
initializer.DataStore = dataStore;
}
initializer.Scopes = scopes;
if (exponentialBackOffPolicy.HasValue)
{
initializer.DefaultExponentialBackOffPolicy = exponentialBackOffPolicy.Value;
}
return new AuthorizationCodeFlow(initializer);
}
/// <summary>Verifies that the token response contains the expected data.</summary>
/// <param name="response">The token response</param>
private void SubtestTokenResponse(TokenResponse response)
{
Assert.Equal("r", response.RefreshToken);
Assert.Equal(100, response.ExpiresInSeconds);
Assert.Equal("b", response.Scope);
}
private class FakeDataStore : IDataStore
{
public string StoredKey { get; private set; }
public string FetchedKey { get; private set; }
public TokenResponse TokenResponse { get; set; }
public Task ClearAsync() => throw new NotImplementedException();
public Task DeleteAsync<T>(string key) => throw new NotImplementedException();
public Task<T> GetAsync<T>(string key)
{
FetchedKey = key;
return Task.FromResult((T) (object) TokenResponse);
}
public Task StoreAsync<T>(string key, T value)
{
StoredKey = key;
// Task.CompletedTask doesn't exist in older frameworks.
return Task.FromResult<object>(null);
}
}
}
}
|