コード例 #1
0
        protected internal virtual async Task <OAuthCredential> GetTemporaryCredentialAsync(
            CancellationToken cancellationToken = default)
        {
            using var request             = new HttpRequestMessage(HttpMethod.Post, _options.TemporaryCredentialRequestUri);
            request.Headers.Authorization = _signer.GetAuthorizationHeader(
                request.Method,
                request.RequestUri.IsAbsoluteUri
                    ? request.RequestUri
                    : new Uri(_httpClient.BaseAddress, request.RequestUri),
                _options,
                new Dictionary <string, StringValues>
            {
                [OAuthDefaults.OAuthCallback] = _options.CallBack == null
                        ? OAuthDefaults.OutOfBand
                        : _options.CallBack.AbsoluteUri
            });
            using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            if (!string.Equals(response.Content.Headers?.ContentType?.MediaType, UrlEncodedContentType, StringComparison.OrdinalIgnoreCase))
            {
                throw new HttpRequestException($"Invalid response with media-type: {response.Content.Headers?.ContentType?.MediaType}");
            }
            var urlEncoded = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var formData = QueryHelpers.ParseQuery(urlEncoded);

            HandleOAuthException(response, formData);
            return(new OAuthCredential(formData[OAuthDefaults.OAuthToken], formData[OAuthDefaults.OAuthTokenSecret]));
        }
コード例 #2
0
        public async Task HttpClient_AccessProtectedResourceWithAuthorizationHeader_ShouldAuthorized()
        {
            // Arrange
            var services = new ServiceCollection()
                           .AddOAuthHttpClient <OAuthHttpClient>((_, handlerOptions) =>
            {
                handlerOptions.ClientCredentials = new OAuthCredential(
                    _configuration["OAuth:ClientId"],
                    _configuration["OAuth:ClientSecret"]);
                handlerOptions.TokenCredentials = _tokenCredentials;
                if (_mockHttp != null)
                {
                    var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                                    .ToString(CultureInfo.InvariantCulture);
                    var nonce = generateNonce();
                    handlerOptions.TimestampProvider = () => timestamp;
                    handlerOptions.NonceProvider     = () => nonce;
                }
            })
                           .ConfigurePrimaryHttpMessageHandler(_ => _mockHttp ?? new HttpClientHandler() as HttpMessageHandler)
                           .Services.BuildServiceProvider();
            var client      = services.GetRequiredService <OAuthHttpClient>();
            var options     = services.GetRequiredService <IOptions <OAuthHttpHandlerOptions> >();
            var resourceUri = _configuration.GetValue <Uri>("Request:Uri");

            _mockHttp?.Expect(HttpMethod.Get, resourceUri.AbsoluteUri)
            .WithHeaders("Authorization", _signer.GetAuthorizationHeader(
                             HttpMethod.Get, resourceUri, options.Value, QueryHelpers.ParseQuery(resourceUri.Query),
                             _tokenCredentials).ToString())
            .Respond(HttpStatusCode.OK);

            // Act
            var response = await client.HttpClient.GetAsync(resourceUri).ConfigureAwait(false);

            // Assert
            Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            _mockHttp?.VerifyNoOutstandingExpectation();
            _mockHttp?.VerifyNoOutstandingRequest();
        }