Files
PetriePanel/WebAPI/Data/OIDCService.cs
littlefoot 320d939c76 Authentication finally moved to the dotnet way in webapi, ready to be added to to deal with users and such
Introspection access point properly uses basic auth of client id and secret to access
2021-10-14 20:54:58 -04:00

54 lines
2.0 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;
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;
}
}
}