< Summary

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

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.ctor(...)100%110%
HandleAuthenticateAsync()0%660%
TryGetApiKey(...)0%880%

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)
 022        : base(options, logger, encoder)
 023    {
 024    }
 25
 26    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
 027    {
 028        if (!TryGetApiKey(out var apiKey))
 029            return Task.FromResult(AuthenticateResult.NoResult());
 30
 031        var validKey = Options.ValidKeys.FirstOrDefault(k => k.Key == apiKey);
 032        if (validKey == null)
 033            return Task.FromResult(AuthenticateResult.Fail("Invalid API key"));
 34
 035        var claims = new List<Claim>
 036        {
 037            new(ClaimTypes.Name, validKey.Name),
 038            new(ClaimTypes.NameIdentifier, validKey.Key),
 039        };
 040        foreach (var role in validKey.Roles)
 041            claims.Add(new Claim(ClaimTypes.Role, role));
 42
 043        var identity = new ClaimsIdentity(claims, SchemeName);
 044        var principal = new ClaimsPrincipal(identity);
 045        var ticket = new AuthenticationTicket(principal, SchemeName);
 46
 047        return Task.FromResult(AuthenticateResult.Success(ticket));
 048    }
 49
 50    private bool TryGetApiKey(out string apiKey)
 051    {
 052        apiKey = "";
 53
 054        if (Request.Headers.TryGetValue(ApiKeyHeaderName, out var headerValue) &&
 055            !string.IsNullOrWhiteSpace(headerValue))
 056        {
 057            apiKey = headerValue.ToString();
 058            return true;
 59        }
 60
 061        if (Request.Query.TryGetValue(ApiKeyQueryName, out var queryValue) &&
 062            !string.IsNullOrWhiteSpace(queryValue))
 063        {
 064            apiKey = queryValue.ToString();
 065            return true;
 66        }
 67
 068        return false;
 069    }
 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{
 85    public required string Key { get; init; }
 86    public required string Name { get; init; }
 87    public List<string> Roles { get; init; } = [];
 88}