FarmMapsApiClient_KB34_MAST/FarmmapsApi/Services/OpenIdConnectService.cs

68 lines
2.4 KiB
C#

using System;
using System.Net.Http;
using System.Threading.Tasks;
using FarmmapsApi.Models;
using IdentityModel;
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> GetTokenUsernamePasswordAsync(string tokenEndpointUrl, string grantClientId, string username, string password)
{
return await _httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest()
{
Address = tokenEndpointUrl,
UserName = username,
Password = password,
ClientId = grantClientId,
GrantType = OidcConstants.GrantTypes.Password,
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
});
}
}
}