コード例 #1
0
        /// <summary>
        /// Execute example
        /// </summary>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The task</returns>
        public async Task Execute(CancellationToken cancellationToken)
        {
            string username = _options.Value.UserName;
            string password = _options.Value.Password;

            var request = new OAuth2TokenV1Request
            {
                GrantType = OAuth2V1Constants.GrantTypes.Password,
                UserName  = username,
                Password  = password,
            };

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

            Require.NotNull(response, nameof(response));
        }
コード例 #2
0
        private async Task <string> GetToken(IRestClient client, CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.UtcNow;

            if (_token != null &&
                _token.Expires > now)
            {
                return(_token.AccessToken);
            }

            string username = _options.Value.UserName;
            string password = _options.Value.Password;

            var model = new OAuth2TokenV1Request
            {
                GrantType = OAuth2V1Constants.GrantTypes.Password,
                UserName  = username,
                Password  = password
            };

            var pathProvider = new PathProvider <OAuth2TokenV1Request>();

            var path = pathProvider.GetPath(model);

            var request = new RestRequest(path, Method.POST);

            var factory = new QueryStringBuilderFactory();

            _ = request.AddHeader("cache-control", "no-cache");

            string encoded = factory.Create()
                             .Add(model)
                             .ToString();

            _ = request.AddParameter(
                ContentTypeConstants.Application.FormUrlEncoded,
                encoded,
                ContentTypeConstants.Application.FormUrlEncoded,
                ParameterType.RequestBody);

            var response = await client
                           .ExecuteAsync <OAuth2TokenV1Response>(request, cancellationToken)
                           .ConfigureAwait(Await.Default);

            if (response.IsSuccessful == true)
            {
                _token = response.Data;

                var expires = DateTimeOffset.UtcNow;

                if (_token.ExpiresIn.HasValue == true)
                {
                    expires = expires
                              .AddSeconds(_token.ExpiresIn.Value)
                              .AddMinutes(-2);
                }

                _token.Expires = expires;

                return(_token.AccessToken);
            }

            return(null);
        }