コード例 #1
0
        /// <inheritdoc/>
        public async Task <string> GetClientAccessTokenAsync(string clientName = "default")
        {
            var item = await _clientAccessTokenCache.GetAsync(clientName);

            if (item != null)
            {
                return(item.AccessToken);
            }

            try
            {
                return(await _clientTokenRequestDictionary.GetOrAdd(clientName, (string _) =>
                {
                    return new Lazy <Task <string> >(async() =>
                    {
                        var response = await _tokenEndpointService.RequestClientAccessToken(clientName);

                        if (response.IsError)
                        {
                            _logger.LogError("Error requesting access token for client {clientName}. Error = {error}", clientName, response.Error);
                            return null;
                        }

                        await _clientAccessTokenCache.SetAsync(clientName, response.AccessToken, response.ExpiresIn);
                        return response.AccessToken;
                    });
                }).Value);
            }
            finally
            {
                _clientTokenRequestDictionary.TryRemove(clientName, out _);
            }
        }
        /// <inheritdoc/>
        public async Task <string> GetClientAccessTokenAsync(
            string clientName = AccessTokenManagementDefaults.DefaultTokenClientName,
            ClientAccessTokenParameters parameters = null,
            CancellationToken cancellationToken    = default)
        {
            parameters ??= new ClientAccessTokenParameters();

            if (parameters.ForceRenewal == false)
            {
                var item = await _clientAccessTokenCache.GetAsync(clientName, parameters, cancellationToken);

                if (item != null)
                {
                    return(item.AccessToken);
                }
            }

            try
            {
                return(await _sync.Dictionary.GetOrAdd(clientName, _ =>
                {
                    return new Lazy <Task <string> >(async() =>
                    {
                        var response = await _tokenEndpointService.RequestClientAccessToken(clientName, parameters, cancellationToken);

                        if (response.IsError)
                        {
                            _logger.LogError("Error requesting access token for client {clientName}. Error = {error}", clientName, response.Error);
                            return null;
                        }

                        await _clientAccessTokenCache.SetAsync(clientName, response.AccessToken, response.ExpiresIn, parameters, cancellationToken);
                        return response.AccessToken;
                    });
                }).Value);
            }
            finally
            {
                _sync.Dictionary.TryRemove(clientName, out _);
            }
        }