Beispiel #1
0
        /// <summary>
        /// Set bearer token and execute request
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The response</returns>
        public async Task <ApiResponse <TResponse> > Execute(ApiRequest <TRequest> request, CancellationToken cancellationToken)
        {
            Argument.NotNull(request, nameof(request));

            if (request.Anonymous != true &&
                request.Credentials.Kind == CredentialsKind.Default)
            {
                if (request.BearerToken == null)
                {
                    request.BearerToken = new ApiBearerToken();
                }

                if (request.BearerToken.HasToken != true)
                {
                    var tokenResponse = await _bearerTokenProvider
                                        .GetToken(request, cancellationToken)
                                        .ConfigureAwait(Await.Default);

                    if (tokenResponse.Response.IsSuccessful == true)
                    {
                        request.BearerToken.Token = tokenResponse.AccessToken;
                    }
                }
            }

            var response = await _apiClient
                           .Execute(request, cancellationToken)
                           .ConfigureAwait(Await.Default);

            return(response);
        }
Beispiel #2
0
        /// <summary>
        /// Get bearer token, from cache or request new
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The token response</returns>
        public async Task <BearerTokenResponse> GetToken(ApiRequest request, CancellationToken cancellationToken)
        {
            Argument.NotNull(request, nameof(request));

            var key = _converter.Convert(request)
                      .ThrowIfNoValue()
                      .Value;

            if (_cache.TryGetValue(key, out var tokenResponse) == true)
            {
                var timespan = tokenResponse.Expires - _dateTimeProvider.UtcNow;

                if (timespan < minLifetime)
                {
                    _cache.Remove(key);

                    tokenResponse = null;
                }
            }

            if (tokenResponse == null)
            {
                tokenResponse = await _bearerTokenProvider
                                .GetToken(request, cancellationToken)
                                .ConfigureAwait(Await.Default);

                if (tokenResponse.Response.IsSuccessful == true)
                {
                    _cache.Add(key, tokenResponse);
                }
            }

            return(tokenResponse);
        }
        /// <summary>
        /// Get bearer token and ensure an access token is returned
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The token response</returns>
        public async Task <BearerTokenResponse> GetToken(ApiRequest request, CancellationToken cancellationToken)
        {
            Argument.NotNull(request, nameof(request));

            var context = (
                request.Credentials.Username,
                request.Context.EndPoint
                );

            string message = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1}",
                nameof(GetToken),
                context);

            Console.WriteLine(message);

            Debug.WriteLine(message);

            var tokenResponse = await _bearerTokenProvider
                                .GetToken(request, cancellationToken)
                                .ConfigureAwait(Await.Default);

            return(tokenResponse);
        }
        /// <summary>
        /// Get bearer token and adjust expiration of bearer tokens to our idea of time
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The token response</returns>
        public async Task <BearerTokenResponse> GetToken(ApiRequest request, CancellationToken cancellationToken)
        {
            Argument.NotNull(request, nameof(request));

            var tokenResponse = await _bearerTokenProvider
                                .GetToken(request, cancellationToken)
                                .ConfigureAwait(Await.Default);

            if (tokenResponse.Response.IsSuccessful == true)
            {
                double?expiresIn = tokenResponse.ExpiresIn;

                Require.NotNull(expiresIn, nameof(expiresIn));

                // Lower expiration to reduce the chance of using an expired token
                expiresIn *= 0.9D;

                var now = _dateTimeProvider.UtcNow;

                var expires = now.AddSeconds(expiresIn.Value);

                tokenResponse.Expires = expires;
            }

            return(tokenResponse);
        }
Beispiel #5
0
        public override async Task <HttpClient> GetHttpClient()
        {
            HttpClient httpClient = base.CreateHttpClient();

            string token = await _bearerTokenProvider.GetToken();

            if (string.IsNullOrWhiteSpace(token))
            {
                throw new MissingBearerTokenException("Null or empty token from bearer token provider");
            }

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            return(httpClient);
        }
Beispiel #6
0
        public void ApiClientTestBaseSetUp()
        {
            _messageHandler = new HttpMessageHandlerStub();

            ClientFactory = Substitute.For <IHttpClientFactory>();

            ClientFactory.CreateClient(Arg.Any <string>())
            .Returns(new HttpClient(_messageHandler)
            {
                BaseAddress = new Uri(HttpStubUri)
            });

            _bearerToken = NewRandomString();

            BearerTokenProvider = Substitute.For <IBearerTokenProvider>();

            BearerTokenProvider.GetToken()
            .Returns(_bearerToken);
        }
Beispiel #7
0
        /// <summary>
        /// Get bearer token and ensure an access token is returned
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The token response</returns>
        public async Task <BearerTokenResponse> GetToken(ApiRequest request, CancellationToken cancellationToken)
        {
            Argument.NotNull(request, nameof(request));

            var tokenResponse = await _bearerTokenProvider
                                .GetToken(request, cancellationToken)
                                .ConfigureAwait(Await.Default);

            if (tokenResponse.Response.IsSuccessful != true)
            {
                const string message = "Failed to acquire access token";

                if (tokenResponse.Response.ErrorException != null)
                {
                    throw new ApiClientException(message, tokenResponse.Response.ErrorException);
                }
                else
                {
                    throw new ApiClientException(message);
                }
            }

            return(tokenResponse);
        }