FarmMapsApiClient/FarmmapsApi/Services/OpenIdConnectService.cs

54 lines
1.8 KiB
C#
Raw Permalink Normal View History

2020-03-24 08:47:08 +00:00
using System;
using System.Net.Http;
using System.Threading.Tasks;
using FarmmapsApi.Models;
using IdentityModel.Client;
namespace FarmmapsApi.Services
{
public class OpenIdConnectService
{
private readonly IDiscoveryCache _discoveryCache;
private readonly Configuration _configuration;
private readonly HttpClient _httpClient;
public OpenIdConnectService(IDiscoveryCache discoveryCache,
IHttpClientFactory httpFactory, Configuration configuration)
{
_discoveryCache = discoveryCache;
_configuration = configuration;
_httpClient = httpFactory.CreateClient();
}
public async Task<DiscoveryDocumentResponse> GetDiscoveryDocumentAsync()
{
var disco = await _discoveryCache.GetAsync();
if (disco.IsError)
throw new Exception(disco.Error);
return disco;
}
public async Task<TokenResponse> GetTokenClientCredentialsAsync(string tokenEndpointUrl, string clientId, string clientSecret)
{
return await _httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest()
{
Address = tokenEndpointUrl,
ClientId = clientId,
ClientSecret = clientSecret,
Scope = string.Join(" ", _configuration.Scopes)
});
}
public async Task<TokenResponse> RefreshTokensAsync(string tokenEndpointUrl, string refreshToken)
{
return await _httpClient.RequestRefreshTokenAsync(new RefreshTokenRequest()
{
Address = tokenEndpointUrl,
ClientId = _configuration.ClientId,
ClientSecret = _configuration.ClientSecret,
RefreshToken = refreshToken
});
}
}
}