Introspection access point properly uses basic auth of client id and secret to access
58 lines
2.1 KiB
C#
58 lines
2.1 KiB
C#
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Text.Encodings.Web;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.Net.Http.Headers;
|
|
using WebAPI.Data;
|
|
|
|
namespace WebAPI.Auth
|
|
{
|
|
public class OIDCTokenAuthenticationHandler : AuthenticationHandler<OIDCTokenAuthenticationOptions>
|
|
{
|
|
private readonly OIDCService _oidcService;
|
|
public OIDCTokenAuthenticationHandler(IOptionsMonitor<OIDCTokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, OIDCService oidcService) : base(options, logger, encoder, clock)
|
|
{
|
|
_oidcService = oidcService;
|
|
}
|
|
|
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
{
|
|
var bearerToken = Request.Headers[HeaderNames.Authorization].FirstOrDefault() ?? "";
|
|
if (string.IsNullOrEmpty(bearerToken))
|
|
{
|
|
return AuthenticateResult.Fail("no token");
|
|
}
|
|
|
|
var token = bearerToken.Split(" ").ElementAt(1);
|
|
if (!await _oidcService.ValidateAccessToken(token))
|
|
{
|
|
return AuthenticateResult.Fail("failed to validate token");
|
|
}
|
|
|
|
var identity = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Authentication, token)
|
|
}, Scheme.Name);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name));
|
|
}
|
|
}
|
|
|
|
public class OIDCTokenAuthenticationOptions : AuthenticationSchemeOptions
|
|
{
|
|
public string OIDCIntrospectionEndpoint { get; set; }
|
|
public string OIDCClientId { get; set; }
|
|
public string OIDCClientSecret { get; set; }
|
|
|
|
}
|
|
|
|
public class OIDCTokenAuthenticationDefaults
|
|
{
|
|
public static string DefaultScheme => "OIDCAuthentication";
|
|
}
|
|
} |