private async Task <AccessTokenResponse> _getToken <TRequest>(TRequest request, CancellationToken cancellationToken = default) { var key = (string)_getKey((dynamic)request); var res = await _accessTokenResponseCachePolicy.ExecuteAsync( (_, ctk) => _inner.GetTokenAsync((dynamic)request, ctk), new Context(key), cancellationToken); return(res); }
public async Task Invoke(HttpContext context) { System.Net.Http.Headers.AuthenticationHeaderValue authHeader; if (System.Net.Http.Headers.AuthenticationHeaderValue.TryParse(context.Request.Headers["Authorization"], out authHeader) || System.Net.Http.Headers.AuthenticationHeaderValue.TryParse(context.Request.Headers["WWW-Authenticate"], out authHeader) || System.Net.Http.Headers.AuthenticationHeaderValue.TryParse(context.Request.Headers["Proxy-Authenticate"], out authHeader) ) { if ("Basic".Equals(authHeader.Scheme, StringComparison.OrdinalIgnoreCase)) { try { string parameter = Encoding.UTF8.GetString( Convert.FromBase64String( authHeader.Parameter)); var parts = parameter.Split(':'); if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[0]) && !string.IsNullOrWhiteSpace(parts[1])) { string userName = parts[0]; string password = parts[1]; var accessToken = await _policy.ExecuteAsync(async (ct) => { var result = await _auth0.GetTokenAsync(new ResourceOwnerTokenRequest() { Audience = _config.Audience, ClientId = _config.ProxyClientId, Username = userName, Password = password, ClientSecret = _config.ProxySecret, Realm = _config.Realm, Scope = "openid profile email", }); return(result.AccessToken); }, context.RequestAborted, true); context.Request.Headers["Authorization"] = $@"Bearer {accessToken}"; } } catch { } } } await _next(context); }
private async Task <AccessTokenResponse> _getToken <TRequest>(TRequest request) { var key = (string)_getKey((dynamic)request); var task = _pendingTasks.GetOrAdd( key, k => _accessTokenResponseCachePolicy.ExecuteAsync( ctx => _inner.GetTokenAsync((dynamic)request), new Context(k) ) ) as Task <AccessTokenResponse>; var res = await task; _pendingTasks.TryRemove(key, out var _); return(res); }
private async Task <string> _getAuth0AccessToken(CancellationToken ctk = default(CancellationToken)) { try { var result = await Policy .Handle <Exception>() .WaitAndRetryAsync(3, r => TimeSpan.FromSeconds(3)) .ExecuteAsync(() => _auth0.GetTokenAsync(new ClientCredentialsTokenRequest { Audience = _config.ApiIdentifier, ClientId = _config.ClientID, ClientSecret = _config.ClientKey })) ; return(result.AccessToken); } catch (Exception ex) { throw new AuthenticationException("Failed to acquire token, check credentials", ex); } }