70 lines
2.7 KiB
C#
70 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using WebAPI.Data.Dto.OIDC;
|
|
|
|
namespace WebAPI.Data
|
|
{
|
|
public class OIDCService
|
|
{
|
|
protected class IntrospectionResponse
|
|
{
|
|
public bool Active { get; set; }
|
|
}
|
|
private HttpClient _httpClient { get; set; }
|
|
private ILogger<OIDCService> _logger { get; set; }
|
|
public OIDCService(ILogger<OIDCService> logger)
|
|
{
|
|
_logger = logger;
|
|
_httpClient = new HttpClient();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simple check of an OIDC access token by attempting to hit the userinfo endpoint.
|
|
/// </summary>
|
|
/// <param name="accessToken">access token to check</param>
|
|
/// <returns>success</returns>
|
|
public async Task<bool> ValidateAccessToken(string accessToken)
|
|
{
|
|
Uri requestUri = new Uri($"https://{AppSettings.OIDCIntrospectionEndpoint}");
|
|
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
|
|
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>()
|
|
{
|
|
{"token", accessToken}
|
|
});
|
|
string encodedAuth = Convert.ToBase64String(Encoding.GetEncoding(Encoding.Latin1.CodePage)
|
|
.GetBytes($"{AppSettings.OIDCClientId}:{AppSettings.OIDCClientSecret}"));
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedAuth);
|
|
HttpResponseMessage response = await _httpClient.SendAsync(request);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var responsecontent = await response.Content.ReadAsStringAsync();
|
|
return JsonConvert.DeserializeObject<IntrospectionResponse>(responsecontent).Active;
|
|
}
|
|
|
|
public async Task<OIDCUserInfoResponse> GetTokenDetails(string accessToken)
|
|
{
|
|
HttpRequestMessage requestMessage =
|
|
new HttpRequestMessage(HttpMethod.Get, $"https://{AppSettings.OIDCUserInfoEndpoint}");
|
|
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
|
HttpResponseMessage response = await _httpClient.SendAsync(requestMessage);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var responsecontent = await response.Content.ReadAsStringAsync();
|
|
return JsonConvert.DeserializeObject<OIDCUserInfoResponse>(responsecontent);
|
|
}
|
|
|
|
}
|
|
} |