Initial commit: Add project files
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace KArtSell.Host.Security;
|
||||
|
||||
public sealed class FailClosedAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
=> Task.FromResult(AuthenticateResult.Fail(
|
||||
"Authentication provider is not configured. The service is fail-closed."));
|
||||
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user