< Summary

Information
Class: Intentum.AspNetCore.Auth.ApiKeyEntry
Assembly: Intentum.AspNetCore
File(s): /home/runner/work/Intentum/Intentum/src/Intentum.AspNetCore/Auth/ApiKeyAuthenticationHandler.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 3
Coverable lines: 3
Total lines: 88
Line coverage: 0%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

File(s)

/home/runner/work/Intentum/Intentum/src/Intentum.AspNetCore/Auth/ApiKeyAuthenticationHandler.cs

#LineLine coverage
 1using System.Security.Claims;
 2using System.Text.Encodings.Web;
 3using Microsoft.AspNetCore.Authentication;
 4using Microsoft.Extensions.Logging;
 5using Microsoft.Extensions.Options;
 6
 7namespace Intentum.AspNetCore.Auth;
 8
 9/// <summary>
 10/// Authentication handler that validates API keys from the X-Api-Key header or query parameter.
 11/// </summary>
 12public sealed class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
 13{
 14    public const string SchemeName = "ApiKey";
 15    private const string ApiKeyHeaderName = "X-Api-Key";
 16    private const string ApiKeyQueryName = "api_key";
 17
 18    public ApiKeyAuthenticationHandler(
 19        IOptionsMonitor<ApiKeyAuthenticationOptions> options,
 20        ILoggerFactory logger,
 21        UrlEncoder encoder)
 22        : base(options, logger, encoder)
 23    {
 24    }
 25
 26    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
 27    {
 28        if (!TryGetApiKey(out var apiKey))
 29            return Task.FromResult(AuthenticateResult.NoResult());
 30
 31        var validKey = Options.ValidKeys.FirstOrDefault(k => k.Key == apiKey);
 32        if (validKey == null)
 33            return Task.FromResult(AuthenticateResult.Fail("Invalid API key"));
 34
 35        var claims = new List<Claim>
 36        {
 37            new(ClaimTypes.Name, validKey.Name),
 38            new(ClaimTypes.NameIdentifier, validKey.Key),
 39        };
 40        foreach (var role in validKey.Roles)
 41            claims.Add(new Claim(ClaimTypes.Role, role));
 42
 43        var identity = new ClaimsIdentity(claims, SchemeName);
 44        var principal = new ClaimsPrincipal(identity);
 45        var ticket = new AuthenticationTicket(principal, SchemeName);
 46
 47        return Task.FromResult(AuthenticateResult.Success(ticket));
 48    }
 49
 50    private bool TryGetApiKey(out string apiKey)
 51    {
 52        apiKey = "";
 53
 54        if (Request.Headers.TryGetValue(ApiKeyHeaderName, out var headerValue) &&
 55            !string.IsNullOrWhiteSpace(headerValue))
 56        {
 57            apiKey = headerValue.ToString();
 58            return true;
 59        }
 60
 61        if (Request.Query.TryGetValue(ApiKeyQueryName, out var queryValue) &&
 62            !string.IsNullOrWhiteSpace(queryValue))
 63        {
 64            apiKey = queryValue.ToString();
 65            return true;
 66        }
 67
 68        return false;
 69    }
 70}
 71
 72/// <summary>
 73/// Options for API key authentication.
 74/// </summary>
 75public sealed class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
 76{
 77    public List<ApiKeyEntry> ValidKeys { get; set; } = [];
 78}
 79
 80/// <summary>
 81/// Represents a registered API key with associated name and roles.
 82/// </summary>
 83public sealed class ApiKeyEntry
 84{
 085    public required string Key { get; init; }
 086    public required string Name { get; init; }
 087    public List<string> Roles { get; init; } = [];
 88}

Methods/Properties

Key()
Name()
Roles()