pages/Authentication.cs

36 lines
1.4 KiB
C#
Raw Normal View History

2024-12-05 12:28:04 +00:00
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace pages;
public class FixedTokenAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> {
private readonly IConfiguration _configuration;
public FixedTokenAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger,
UrlEncoder encoder, IConfiguration configuration) : base(options, logger, encoder) {
_configuration = configuration;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync() {
string? token = _configuration["API_TOKEN"];
if (string.IsNullOrEmpty(token))
throw new ArgumentException("API_TOKEN not found.");
if (!Request.Headers.TryGetValue("Authorization", out var headerValue))
return Task.FromResult(AuthenticateResult.Fail("No Authorization header."));
string providedToken = headerValue.ToString().Replace("Bearer ", "");
if (providedToken != token)
return Task.FromResult(AuthenticateResult.Fail("Invalid token."));
var identity = new ClaimsIdentity([], Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}