36 lines
1.4 KiB
C#
36 lines
1.4 KiB
C#
|
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));
|
|||
|
}
|
|||
|
}
|