finalizare 1.0
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Infrastructure.Services.Authentication;
|
||||
|
||||
public class ApiKeyAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
ISystemClock clock,
|
||||
IConfiguration configuration)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder, clock)
|
||||
{
|
||||
private const string ApiKeyHeaderName = "ApiKey";
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!Request.Headers.TryGetValue(ApiKeyHeaderName, out var apiKeyHeaderValues))
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
|
||||
var providedApiKey = apiKeyHeaderValues.FirstOrDefault();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(providedApiKey)) return Task.FromResult(AuthenticateResult.NoResult());
|
||||
|
||||
var configuredApiKey = configuration.GetValue<string>("ApiKey");
|
||||
|
||||
if (configuredApiKey.Equals(providedApiKey))
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.Name, "ApiKeyUser") };
|
||||
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Fail("Invalid API Key provided."));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user