47 lines
1.7 KiB
C#
47 lines
1.7 KiB
C#
using System.Security.Claims;
|
|
using System.Text.Encodings.Web;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace KArtSell.Host.Security;
|
|
|
|
/// <summary>
|
|
/// Development-only authentication. Never enable outside Development.
|
|
/// Required headers: X-KArtSell-User and X-KArtSell-Role.
|
|
/// </summary>
|
|
public sealed class DevelopmentHeaderAuthenticationHandler(
|
|
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
|
ILoggerFactory logger,
|
|
UrlEncoder encoder,
|
|
IWebHostEnvironment environment)
|
|
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
|
{
|
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
{
|
|
if (!environment.IsDevelopment())
|
|
{
|
|
return Task.FromResult(AuthenticateResult.Fail(
|
|
"Development header authentication is disabled outside Development."));
|
|
}
|
|
|
|
var user = Request.Headers["X-KArtSell-User"].ToString();
|
|
var role = Request.Headers["X-KArtSell-Role"].ToString();
|
|
if (string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(role))
|
|
{
|
|
return Task.FromResult(AuthenticateResult.NoResult());
|
|
}
|
|
|
|
var claims = new[]
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, user),
|
|
new Claim(ClaimTypes.Name, user),
|
|
new Claim(ClaimTypes.Role, role),
|
|
new Claim("auth_mode", "development_header")
|
|
};
|
|
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
return Task.FromResult(AuthenticateResult.Success(
|
|
new AuthenticationTicket(principal, Scheme.Name)));
|
|
}
|
|
}
|