public static class HttpExtensions { public static async Task HandleToken(this HttpClient client, IHttpContextAccessor httpContextAccessor, string authority, string clientId, string secret, string apiName) { var accessToken = await httpContextAccessor.HttpContext.GetRefreshTokenAsync(authority, clientId, secret, apiName); client.SetBearerToken(accessToken); } private static async Task<string> GetRefreshTokenAsync(this HttpContext httpContext, string authority, string clientId, string secret, string apiName) { var discoveryClient = new DiscoveryClient(authority); var disco = await discoveryClient.GetAsync(); if (disco.IsError) throw new Exception(disco.Error); var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, secret); var tokenResponse = await tokenClient.RequestClientCredentialsAsync(apiName); if (!tokenResponse.IsError) return tokenResponse.AccessToken; return null; } }