AspNetCore.SecurityKey 5.1.0

dotnet add package AspNetCore.SecurityKey --version 5.1.0
                    
NuGet\Install-Package AspNetCore.SecurityKey -Version 5.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AspNetCore.SecurityKey" Version="5.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AspNetCore.SecurityKey" Version="5.1.0" />
                    
Directory.Packages.props
<PackageReference Include="AspNetCore.SecurityKey" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AspNetCore.SecurityKey --version 5.1.0
                    
#r "nuget: AspNetCore.SecurityKey, 5.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AspNetCore.SecurityKey@5.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AspNetCore.SecurityKey&version=5.1.0
                    
Install as a Cake Addin
#tool nuget:?package=AspNetCore.SecurityKey&version=5.1.0
                    
Install as a Cake Tool

Security API Keys for ASP.NET Core

A flexible and lightweight API key authentication library for ASP.NET Core applications that supports multiple authentication patterns and integrates seamlessly with ASP.NET Core's authentication and authorization infrastructure.

Build Project

Coverage Status

AspNetCore.SecurityKey

Table of Contents

Overview

AspNetCore.SecurityKey provides a complete API key authentication solution for ASP.NET Core applications with support for modern development patterns and best practices.

Feature List:

  • Multiple Input Sources - API keys via headers, query parameters, or cookies
  • Flexible Authentication - Works with ASP.NET Core's built-in authentication or as standalone middleware
  • IP Restrictions for API Keys - Limit where valid API keys can be used by IP address and network range (IPv4 and IPv6)
  • Cloudflare and Proxy Support - Works with UseForwardedHeaders() to use the real client IP behind Cloudflare or a proxy
  • Extensible Design - Custom validation and extraction logic support
  • Rich Integration - Controller attributes, middleware, and minimal API support
  • OpenTelemetry Support - Built-in activities, metrics, tags, and exception events for authentication diagnostics
  • High Performance - Minimal overhead with optional caching and timing-attack protection
  • Multiple Deployment Patterns - Attribute-based, middleware, or endpoint filters

Quick Start

  1. Install the package:

    dotnet add package AspNetCore.SecurityKey
    
  2. Configure your API key in appsettings.json:

    {
      "SecurityKey": "your-secret-api-key-here"
    }
    
  3. Register services and secure endpoints:

    builder.Services.AddSecurityKey();
    app.UseSecurityKey(); // Secures all endpoints
    
  4. Call your API with the key:

    curl -H "X-API-KEY: your-secret-api-key-here" https://yourapi.com/endpoint
    

Installation

The library is available on nuget.org via package name AspNetCore.SecurityKey.

Package Manager Console

Install-Package AspNetCore.SecurityKey

.NET CLI

dotnet add package AspNetCore.SecurityKey

PackageReference

<PackageReference Include="AspNetCore.SecurityKey" />

How to Pass API Keys

AspNetCore.SecurityKey supports multiple ways to pass API keys in requests, providing flexibility for different client scenarios:

The most common and secure approach for API-to-API communication:

GET https://api.example.com/users
Accept: application/json
X-API-KEY: 01HSGVBSF99SK6XMJQJYF0X3WQ

Query Parameters

Useful for simple integrations or when headers cannot be easily modified:

GET https://api.example.com/users?X-API-KEY=01HSGVBSF99SK6XMJQJYF0X3WQ
Accept: application/json

⚠️ Security Note: When using query parameters, be aware that API keys may appear in server logs, browser history, and referrer headers. Headers are generally preferred for production use.

Cookies

Ideal for browser-based applications or when API keys need persistence:

GET https://api.example.com/users
Accept: application/json
Cookie: X-API-KEY=01HSGVBSF99SK6XMJQJYF0X3WQ

Configuration

Basic Setup

Configure your API keys in appsettings.json:

{
  "SecurityKey": "01HSGVBSF99SK6XMJQJYF0X3WQ"
}

Multiple API Keys

Support multiple valid API keys using semicolon or comma separation:

{
  "SecurityKey": "01HSGVBGWXWDWTFGTJSYFXXDXQ;01HSGVBSF99SK6XMJQJYF0X3WQ;01HSGVAH2M5WVQYG4YPT7FNK4K8"
}

API keys are compared with an exact, case-sensitive, fixed-time comparison.

Enhanced Configuration Format

To restrict where API keys can be used by IP address or network, use the enhanced configuration format:

{
  "SecurityKey": {
    "AllowedKeys": [
      "01HSGVBGWXWDWTFGTJSYFXXDXQ",
      "01HSGVBSF99SK6XMJQJYF0X3WQ",
      "01HSGVAH2M5WVQYG4YPT7FNK4K8"
    ],
    "AllowedAddresses": [
      "192.168.1.100",
      "10.0.0.1",
      "203.0.113.50",
      "::1"
    ],
    "AllowedNetworks": [
      "192.168.0.0/16",
      "10.0.0.0/8",
      "172.16.0.0/12",
      "2001:db8::/32"
    ]
  }
}

The enhanced format is used when AllowedKeys is present. Blank keys are ignored and surrounding whitespace is trimmed. AllowedAddresses and AllowedNetworks are optional: when set, a request needs a valid key and an allowed address (see Restricting API Keys by IP Address). They never let a request in without a key.

Advanced Options

Customize key extraction and validation behavior:

builder.Services.AddSecurityKey(options =>
{
    // Custom configuration path
    options.ConfigurationName = "Authentication:ApiKey";
    
    // Customize header name (default: "x-api-key")
    options.HeaderName = "API-KEY";
    
    // Customize query parameter name (default: "x-api-key") 
    options.QueryName = "apikey";
    
    // Customize cookie name (default: "x-api-key")
    options.CookieName = "app-api-key";
    
    // Custom authentication scheme name
    options.AuthenticationScheme = "CustomApiKey";
    
    // Claims configuration
    options.ClaimNameType = ClaimTypes.Name;
    options.ClaimRoleType = ClaimTypes.Role;
    options.ClaimIpAddressType = "ipaddr";
    options.ClaimAuthenticationMethodType = ClaimTypes.AuthenticationMethod;
    options.ClaimAuthenticationInstantType = ClaimTypes.AuthenticationInstant;

    // Optional caching for performance
    options.CacheTime = TimeSpan.FromMinutes(5);
});

Security API keys are always compared with an exact, case-sensitive, fixed-time comparison to prevent timing attacks; this is not configurable.

The default SecurityKeyValidator identity always includes a name claim (ClaimNameType). It also adds an authentication method claim (ClaimAuthenticationMethodType) set to the scheme used, an authentication instant claim (ClaimAuthenticationInstantType) set to the UTC time of authentication, and, when an IP address is supplied to Authenticate, an IP address claim (ClaimIpAddressType) set to the caller's address. The ipaddr and ClaimTypes.AuthenticationMethod/ClaimTypes.AuthenticationInstant defaults match the claim names Microsoft Entra ID and WIF use for the same values.

IP Address Restrictions

API keys can be restricted to the IP addresses and networks they are expected to come from. A request then needs a valid API key and an allowed address. The IP check only narrows where keys work; it never lets a request in on its own.

The client address is HttpContext.Connection.RemoteIpAddress. Behind a proxy, UseForwardedHeaders() sets it to the real client.

IPv4 and IPv6, individual addresses, and networks in CIDR notation are supported. IPv4 clients reported as IPv4-mapped IPv6 addresses (such as ::ffff:10.1.2.3, common on dual-stack listeners) match IPv4 entries, and IPv4-mapped entries (such as ::ffff:10.0.0.0/104, the same as 10.0.0.0/8) match IPv4 clients. Entries that cannot be parsed are logged as warnings at startup and ignored.

Restricting API Keys by IP Address

Add AllowedAddresses and AllowedNetworks next to AllowedKeys in the enhanced configuration format:

{
  "SecurityKey": {
    "AllowedKeys": ["your-api-key-here"],
    "AllowedAddresses": [
      "192.168.1.100",      // Specific IPv4 address
      "10.0.0.1",           // Another IPv4 address
      "::1",                // IPv6 localhost
      "2001:db8::1"         // Specific IPv6 address
    ],
    "AllowedNetworks": [
      "192.168.0.0/16",     // Private network range
      "10.0.0.0/8",         // Class A private network
      "172.16.0.0/12",      // Class B private network
      "2001:db8::/32"       // IPv6 network range
    ]
  }
}

How it works:

  1. API key first: A request without a valid API key is rejected, whatever its address
  2. No restrictions: If neither AllowedAddresses nor AllowedNetworks is configured, valid keys are accepted from all addresses
  3. Address matching: The client IP is checked against the AllowedAddresses list for exact matches
  4. Network matching: The client IP is checked against the AllowedNetworks list using CIDR notation
  5. Combined logic: The key is accepted if the IP matches an allowed address OR falls within an allowed network
  6. Fail closed: If the lists contain only entries that cannot be parsed, keys are rejected from every address

No extra setup is needed. The restriction applies wherever API keys are validated: UseSecurityKey(), [SecurityKey], .RequireSecurityKey(), and the authentication handler.

Development Environment

Allow keys only from local development machines:

{
  "SecurityKey": {
    "AllowedKeys": ["dev-key-123"],
    "AllowedAddresses": [
      "127.0.0.1",          // IPv4 localhost
      "::1"                 // IPv6 localhost
    ],
    "AllowedNetworks": [
      "192.168.0.0/16"      // Local network
    ]
  }
}
Corporate Environment

Allow keys only from internal corporate networks:

{
  "SecurityKey": {
    "AllowedKeys": ["corporate-api-key"],
    "AllowedNetworks": [
      "10.0.0.0/8",         // Corporate internal network
      "172.16.0.0/12",      // Secondary corporate network
      "203.0.113.0/24"      // Public-facing servers
    ]
  }
}

Behind Cloudflare or a Reverse Proxy

IP restrictions use HttpContext.Connection.RemoteIpAddress. The library never reads X-Forwarded-For, CF-Connecting-IP, or similar headers itself, because any client can send them.

Behind Cloudflare, a load balancer, or a reverse proxy, every request reaches the application from the proxy's address. Use the ASP.NET Core forwarded headers middleware. For requests that come from one of your known proxies, it replaces the connection address with the client address the proxy reports. The IP restrictions on API keys and the rest of the application (logging, rate limiting) then all see the real client address.

Configure ForwardedHeadersOptions with your proxies, then add the middleware:

using System.Net;
using Microsoft.AspNetCore.HttpOverrides;

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;

    // the reverse proxy or load balancer in front of the application
    options.KnownProxies.Add(IPAddress.Parse("10.0.0.2"));
});

var app = builder.Build();

// first, before UseSecurityKey(), UseAuthentication(), and UseAuthorization()
app.UseForwardedHeaders();
Cloudflare

Cloudflare sends the visitor's address in the CF-Connecting-IP header. Trust it only from Cloudflare's own ranges:

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.ForwardedForHeaderName = "CF-Connecting-IP";

    string[] cloudflareRanges =
    [
        // Cloudflare IPv4 ranges
        "173.245.48.0/20",
        "103.21.244.0/22",
        "103.22.200.0/22",
        "103.31.4.0/22",
        "141.101.64.0/18",
        "108.162.192.0/18",
        "190.93.240.0/20",
        "188.114.96.0/20",
        "197.234.240.0/22",
        "198.41.128.0/17",
        "162.158.0.0/15",
        "104.16.0.0/13",
        "104.24.0.0/14",
        "172.64.0.0/13",
        "131.0.72.0/22",
        // Cloudflare IPv6 ranges
        "2400:cb00::/32",
        "2606:4700::/32",
        "2803:f800::/32",
        "2405:b500::/32",
        "2405:8100::/32",
        "2a06:98c0::/29",
        "2c0f:f248::/32",
    ];

    foreach (var range in cloudflareRanges)
        options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(range));
});

The API key's own restrictions stay in configuration:

{
  "SecurityKey": {
    "AllowedKeys": ["partner-api-key"],
    "AllowedNetworks": ["198.51.100.0/24"]     // partner's real addresses, not Cloudflare's
  }
}

The ranges above are Cloudflare's list at the time of writing. Copy the current list from cloudflare.com/ips (also at https://api.cloudflare.com/client/v4/ips) and review it periodically. A range missing from the list only makes requests from it use the edge address. A range that is no longer Cloudflare's lets whoever owns it set any client address, so remove retired ranges.

If the site is published through Cloudflare Tunnel (cloudflared), requests reach the application from the cloudflared process, not from Cloudflare's ranges. List that address instead, for example options.KnownProxies.Add(IPAddress.Parse("10.0.0.5")). When it runs on the same machine, the loopback defaults already cover it.

Forwarded Headers Options

The main ForwardedHeadersOptions settings:

Option Description Default
ForwardedHeaders Headers to process, such as XForwardedFor \| XForwardedProto None
ForwardedForHeaderName Header with the client address, CF-Connecting-IP for Cloudflare X-Forwarded-For
ForwardLimit Number of proxy hops to process. null removes the limit 1
KnownProxies Proxy IP addresses ::1
KnownIPNetworks Proxy networks 127.0.0.0/8
AllowedHosts Allowed values for the forwarded host header any
RequireHeaderSymmetry Require the same number of entries in every processed header false
ForwardedProtoHeaderName, ForwardedHostHeaderName, ForwardedPrefixHeaderName Other header names ASP.NET Core defaults
  • ForwardedHeaders defaults to None, so the middleware does nothing until it is set
  • Proxies and networks you add are kept alongside the ASP.NET Core loopback defaults
  • To keep proxy addresses in configuration, read them yourself, for example builder.Configuration.GetSection("Proxies").Get<string[]>(), and parse them into KnownProxies or KnownIPNetworks
How the Client Address Is Resolved
  1. Request from an unknown address: the middleware changes nothing, so a client that bypasses the proxy and connects directly cannot choose its address
  2. Request from a known proxy: the client address is taken from ForwardedForHeaderName
  3. Header lists: comma-separated headers such as X-Forwarded-For are read from right to left, one hop per known proxy, up to ForwardLimit hops. Values a client puts at the start of the header are never reached
  4. What SecurityKey sees: the resulting HttpContext.Connection.RemoteIpAddress. Entries the middleware did not use stay in the header, but the library never reads them
Other Proxies and CDNs
Proxy ForwardedForHeaderName Proxy addresses to list
Cloudflare CF-Connecting-IP Cloudflare ranges, or the cloudflared address
Azure Front Door X-Azure-ClientIP Front Door backend ranges (AzureFrontDoor.Backend service tag)
Fastly Fastly-Client-IP Fastly ranges
Akamai True-Client-IP Akamai ranges
nginx, IIS ARR, AWS ALB, and most load balancers X-Forwarded-For The proxy or load balancer addresses

Proxies can be chained. For Cloudflare in front of your own nginx, keep X-Forwarded-For (nginx appends to it), list both, and allow two hops:

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.ForwardLimit = 2;
    options.KnownProxies.Add(IPAddress.Parse("10.0.0.2"));                       // nginx
    options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("173.245.48.0/20"));  // plus the other Cloudflare ranges
});
Keeping Visitors on the Proxy

The forwarded headers middleware stops a direct visitor from faking a client address, but the visitor can still reach the application with its own address. To accept only traffic that came through Cloudflare, also restrict the server's firewall to the Cloudflare ranges.

⚠️ Security Notes

  • Never clear KnownProxies and KnownIPNetworks to "trust everything". The ASPNETCORE_FORWARDEDHEADERS_ENABLED=true environment variable does exactly that, so don't use it when IP checks matter. The middleware would accept forwarded headers from any client, and anyone could choose the address used by IP checks.
  • Keep proxy addresses out of SecurityKey:AllowedAddresses and SecurityKey:AllowedNetworks. A request the middleware does not resolve keeps the proxy's own address.

Upgrading: Earlier versions read the first X-Forwarded-For entry for the IP restrictions on API keys. Clients could set that value themselves. If you relied on it, add UseForwardedHeaders() with your proxies in ForwardedHeadersOptions.

IP Address Considerations

  1. Combine with HTTPS: IP checks should always be combined with HTTPS to prevent man-in-the-middle attacks
  2. Network Ranges: Be careful with broad network ranges like 0.0.0.0/0 or ::/0 as they allow all addresses
  3. Dynamic IPs: Consider that client IPs may change, especially for mobile clients or users behind NAT
  4. Proxy Headers: Validate that your reverse proxy configuration correctly forwards real client IPs
  5. Logging: Monitor failed authentication attempts to detect potential security issues

Usage Patterns

AspNetCore.SecurityKey supports multiple integration patterns to fit different application architectures and security requirements.

1. Middleware Pattern (Global Protection)

Apply API key requirement to all endpoints in your application:

var builder = WebApplication.CreateBuilder(args);

// Register services
builder.Services.AddAuthorization();
builder.Services.AddSecurityKey();

var app = builder.Build();

// Apply security to ALL endpoints
app.UseSecurityKey();
app.UseAuthorization();

// All these endpoints require valid API keys
app.MapGet("/weather", () => WeatherService.GetForecast());
app.MapGet("/users", () => UserService.GetUsers()); 
app.MapGet("/products", () => ProductService.GetProducts());

app.Run();

2. Attribute Pattern (Selective Protection)

Apply API key requirement to specific controllers or actions:

[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    // This action requires API key
    [SecurityKey]
    [HttpGet]
    public IEnumerable<User> GetUsers()
    {
        return UserService.GetUsers();
    }
    
    // This action is public (no API key required)
    [HttpGet("public")]
    public IEnumerable<User> GetPublicUsers()
    {
        return UserService.GetPublicUsers();
    }
}

// Or apply to entire controller
[SecurityKey]
[ApiController]  
[Route("[controller]")]
public class SecureController : ControllerBase
{
    // All actions in this controller require API key
    [HttpGet]
    public IActionResult Get() => Ok();
}

3. Endpoint Filter Pattern (Minimal APIs)

Secure specific minimal API endpoints:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthorization();
builder.Services.AddSecurityKey();

var app = builder.Build();

app.UseAuthorization();

// Public endpoint (no API key required)
app.MapGet("/health", () => "Healthy");

// Secured endpoint using filter
app.MapGet("/users", () => UserService.GetUsers())
   .RequireSecurityKey();

// Multiple endpoints can be grouped
var securedGroup = app.MapGroup("/api/secure")
                     .RequireSecurityKey();

securedGroup.MapGet("/data", () => "Secured data");
securedGroup.MapPost("/action", () => "Secured action");

// Works with any IEndpointConventionBuilder, such as the MCP C# SDK
app.MapMcp("/mcp")
   .RequireSecurityKey();

app.Run();

.RequireSecurityKey() can be applied to any IEndpointConventionBuilder, including RouteHandlerBuilder, RouteGroupBuilder, and builders returned by library Map* methods such as MapMcp(). It adds an endpoint filter, so it applies to endpoints that run endpoint filters: minimal API endpoints (including RequestDelegate endpoints) and controller actions. For other endpoint types, use the authentication scheme with RequireAuthorization().

4. Authentication Scheme Pattern (Full Integration)

Integrate with ASP.NET Core's authentication system:

var builder = WebApplication.CreateBuilder(args);

// Register authentication with SecurityKey scheme
builder.Services
    .AddAuthentication()
    .AddSecurityKey();

builder.Services.AddAuthorization();
builder.Services.AddSecurityKey();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// Use standard authorization attributes
app.MapGet("/users", () => UserService.GetUsers())
   .RequireAuthorization();

// Can also be combined with role-based authorization
app.MapGet("/admin", () => "Admin data")
   .RequireAuthorization("AdminPolicy");

app.Run();

Advanced Customization

Custom Security Key Validation

Implement custom validation logic by creating a class that implements ISecurityKeyValidator:

public class DatabaseSecurityKeyValidator : ISecurityKeyValidator
{
    private readonly IApiKeyRepository _repository;
    private readonly ILogger<DatabaseSecurityKeyValidator> _logger;

    public DatabaseSecurityKeyValidator(
        IApiKeyRepository repository, 
        ILogger<DatabaseSecurityKeyValidator> logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public async ValueTask<bool> Validate(string? value, IPAddress? ipAddress = null, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrEmpty(value))
            return false;

        try
        {
            var apiKey = await _repository.GetApiKeyAsync(value, cancellationToken);
            
            // Never log the key itself, it may be a valid key with a typo or one for another environment
            if (apiKey == null)
            {
                _logger.LogWarning("Unknown API key attempted from IP {IpAddress}", ipAddress);
                return false;
            }

            if (apiKey.IsExpired)
            {
                _logger.LogWarning("Expired API key {KeyId} used", apiKey.Id);
                return false;
            }

            // Validate IP address if restrictions are configured
            if (!IsIpAddressAllowed(ipAddress, apiKey.AllowedIpAddresses, apiKey.AllowedNetworks))
            {
                _logger.LogWarning("API key {KeyId} used from unauthorized IP: {IpAddress}", apiKey.Id, ipAddress);
                return false;
            }

            // Update last used timestamp
            await _repository.UpdateLastUsedAsync(value, DateTime.UtcNow, cancellationToken);
            
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error validating API key");
            return false;
        }
    }

    public async ValueTask<ClaimsIdentity> Authenticate(string? value, IPAddress? ipAddress = null, string? scheme = null, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrEmpty(value) || !await Validate(value, ipAddress, cancellationToken))
            return new ClaimsIdentity();

        var apiKey = await _repository.GetApiKeyAsync(value, cancellationToken);
        if (apiKey?.User == null)
            return new ClaimsIdentity();

        var identity = new ClaimsIdentity(scheme ?? SecurityKeyAuthenticationDefaults.AuthenticationScheme);
        identity.AddClaim(new Claim(ClaimTypes.Name, apiKey.User.Name));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, apiKey.User.Id));
        
        // Add role claims
        foreach (var role in apiKey.User.Roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, role));
        }

        return identity;
    }

    private bool IsIpAddressAllowed(IPAddress? ipAddress, string[]? allowedAddresses, string[]? allowedNetworks)
    {
        // Use the built-in whitelist functionality
        return SecurityKeyWhitelist.IsIpAllowed(ipAddress, allowedAddresses, allowedNetworks);
    }
}

// Register custom validator. It is a singleton, so its dependencies must be singletons too.
// For scoped dependencies such as a DbContext, see "Validators with Scoped Dependencies" below.
builder.Services.AddSingleton<IApiKeyRepository, ApiKeyRepository>();
builder.Services.AddSecurityKey<DatabaseSecurityKeyValidator>();

Custom Security Key Extraction

Create custom extraction logic for non-standard scenarios:

public class CustomSecurityKeyExtractor : ISecurityKeyExtractor
{
    private readonly ILogger<CustomSecurityKeyExtractor> _logger;

    public CustomSecurityKeyExtractor(ILogger<CustomSecurityKeyExtractor> logger)
    {
        _logger = logger;
    }

    public string? GetKey(HttpContext? context)
    {
        if (context == null)
            return null;

        // Try multiple sources in priority order
        
        // 1. Authorization header with Bearer scheme
        if (context.Request.Headers.TryGetValue("Authorization", out var authHeader))
        {
            var auth = authHeader.FirstOrDefault();
            if (!string.IsNullOrEmpty(auth) && auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                return auth.Substring(7); // Remove "Bearer " prefix
            }
        }

        // 2. Custom header
        if (context.Request.Headers.TryGetValue("X-API-TOKEN", out var tokenHeader))
        {
            return tokenHeader.FirstOrDefault();
        }

        // 3. Query parameter
        if (context.Request.Query.TryGetValue("access_token", out var queryToken))
        {
            return queryToken.FirstOrDefault();
        }

        // 4. Form data (for POST requests)
        if (context.Request.HasFormContentType && 
            context.Request.Form.TryGetValue("api_key", out var formKey))
        {
            return formKey.FirstOrDefault();
        }

        _logger.LogDebug("No API key found in request");
        return null;
    }

    // Client IP address used for the IP restrictions configured for API keys
    public IPAddress? GetRemoteAddress(HttpContext? context)
    {
        return context?.Connection.RemoteIpAddress;
    }
}

// Register both custom validator and extractor
builder.Services.AddSecurityKey<DatabaseSecurityKeyValidator, CustomSecurityKeyExtractor>();

IP restrictions on API keys are only as reliable as GetRemoteAddress, so it must never return a value the client controls, such as an X-Forwarded-For entry. Return context.Connection.RemoteIpAddress and let UseForwardedHeaders() resolve proxies.

To change only how the key is found, derive from SecurityKeyExtractor and override GetKey. Its methods are virtual, so the IP address handling stays as it is. This one also accepts the key as a bearer token, when the usual header, query string, and cookie carry none:

public class BearerSecurityKeyExtractor(IOptions<SecurityKeyOptions> options)
    : SecurityKeyExtractor(options)
{
    public override string? GetKey(HttpContext? context)
    {
        // the usual locations first, so a bearer token meant for another scheme,
        // such as a JWT, does not hide a key sent in the x-api-key header
        var key = base.GetKey(context);
        if (!string.IsNullOrEmpty(key))
            return key;

        var authorization = context?.Request.Headers.Authorization.ToString();
        if (authorization?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) != true)
            return null;

        var token = authorization["Bearer ".Length..].Trim();
        return token.Length > 0 ? token : null;
    }
}

Provider Services and Service Keys

The validator (ISecurityKeyValidator) and extractor (ISecurityKeyExtractor) come from dependency injection. Authentication schemes use keyed services with the scheme name as the service key, so each scheme can have its own providers.

Where each component gets its providers:

Component Validator and extractor
UseSecurityKey(), [SecurityKey], .RequireSecurityKey() endpoint filter The unkeyed services, injected once
SecurityKey authentication handler, and schemes added with AddSecurityKey("name") The keyed services named by SecurityKeyAuthenticationSchemeOptions.ProviderServiceKey, which AddSecurityKey always sets to the scheme name

What each registration adds:

Registration Unkeyed singletons Keyed services
services.AddSecurityKey<TValidator, TExtractor>() TValidator, TExtractor None
AddAuthentication().AddSecurityKey<TValidator, TExtractor>(scheme) TValidator, TExtractor TValidator, TExtractor as scoped services under the scheme name

Overloads without type arguments use SecurityKeyValidator and SecurityKeyExtractor, and the scheme name defaults to SecurityKey.

  • First registration wins: Each service is added only when none is registered for the same key yet. After services.AddSecurityKey<ConfigValidator>() followed by AddAuthentication().AddSecurityKey<DatabaseValidator>(), the middleware and filters use ConfigValidator, while the authentication handler uses DatabaseValidator. A keyed service you register yourself under a scheme name is used instead of the scheme's own
  • ProviderServiceKey on AddSecurityKey schemes: It is set to the scheme name after your options delegate runs, so a value set there is replaced. To change a scheme's providers, register them under the scheme name
  • One configuration for the built-in providers: The service key selects providers, not configuration. Every scheme that uses the built-in providers reads the same configuration section, see Configuration Sections per Scheme
Validators with Scoped Dependencies

The unkeyed validator is a singleton, so it cannot depend on scoped services such as a DbContext. AddSecurityKey<TValidator>() registers TValidator that way, both on IServiceCollection and on AuthenticationBuilder. In Development, where ASP.NET Core validates service scopes at startup, builder.Build() then fails with Cannot consume scoped service '...' from singleton 'AspNetCore.SecurityKey.ISecurityKeyValidator'. In other environments, any component that uses the unkeyed validator keeps one instance of the scoped service for the lifetime of the application.

Instead, register the validator yourself as a keyed scoped service under the scheme name, and let AddSecurityKey() add the default unkeyed providers:

builder.Services.AddScoped<IApiKeyRepository, ApiKeyRepository>();

// Resolved per request by the SecurityKey authentication handler
builder.Services.AddKeyedScoped<ISecurityKeyValidator, DatabaseSecurityKeyValidator>(
    SecurityKeyAuthenticationDefaults.AuthenticationScheme);

// Keeps the keyed validator above, and adds the default extractor and unkeyed providers
builder.Services
    .AddAuthentication()
    .AddSecurityKey();

The middleware, [SecurityKey] attribute, and .RequireSecurityKey() endpoint filter still use the configuration-based SecurityKeyValidator, so protect endpoints with the authentication scheme instead, for example with RequireAuthorization().

Different Providers per Scheme

Each scheme added with AddSecurityKey has its own keyed providers, so callers can be validated differently per endpoint:

builder.Services
    .AddAuthentication()
    .AddSecurityKey()                                          // keys from the "SecurityKey" configuration section
    .AddSecurityKey<PartnerSecurityKeyValidator>("Partner");   // keys from the partner store

app.MapGet("/partner/orders", () => OrderService.GetOrders())
   .RequireAuthorization(policy => policy
       .AddAuthenticationSchemes("Partner")
       .RequireAuthenticatedUser());

The Partner scheme resolves PartnerSecurityKeyValidator with the Partner key. The unkeyed validator stays SecurityKeyValidator, because the first call registered it. Require a Partner caller with AddAuthenticationSchemes("Partner") and RequireAuthenticatedUser(), as above.

Configuration Sections per Scheme

The built-in SecurityKeyValidator and SecurityKeyExtractor read the single SecurityKeyOptions configured with AddSecurityKey(options => ...). Every scheme that uses them reads keys from the same ConfigurationName section, and from the same header, query, and cookie names. AddSecurityKey("Partner") on its own accepts exactly the keys the SecurityKey scheme accepts.

To give a scheme its own configuration section, register its providers under the scheme name, created with their own options:

using Microsoft.Extensions.Options;

var partnerOptions = Options.Create(new SecurityKeyOptions
{
    ConfigurationName = "PartnerKeys",   // keys from the "PartnerKeys" section
    HeaderName = "x-partner-key",
});

builder.Services.AddKeyedSingleton<ISecurityKeyValidator>("Partner", (services, _) =>
    new SecurityKeyValidator(
        services.GetRequiredService<IConfiguration>(),
        partnerOptions,
        services.GetRequiredService<ILogger<SecurityKeyValidator>>()));

builder.Services.AddKeyedSingleton<ISecurityKeyExtractor>("Partner", (_, _) =>
    new SecurityKeyExtractor(partnerOptions));

builder.Services
    .AddAuthentication()
    .AddSecurityKey()             // "SecurityKey" section, x-api-key header
    .AddSecurityKey("Partner");   // "PartnerKeys" section, x-partner-key header
{
  "SecurityKey": "01HSGVBSF99SK6XMJQJYF0X3WQ",
  "PartnerKeys": {
    "AllowedKeys": ["01HSGVBGWXWDWTFGTJSYFXXDXQ"],
    "AllowedNetworks": ["198.51.100.0/24"]
  }
}
  • Separate keys: The Partner scheme accepts only keys from PartnerKeys, sent in the x-partner-key header, and the SecurityKey scheme does not accept them
  • Same formats: The section supports the same formats as SecurityKey, including IP restrictions with AllowedAddresses and AllowedNetworks
  • Separate options: partnerOptions is its own instance, so settings made with AddSecurityKey(options => ...), such as CacheTime or ClaimNameType, do not apply to it. Set them on partnerOptions as well

Rate Limiting Integration

Combine with ASP.NET Core rate limiting for enhanced security:

builder.Services.AddRateLimiter(options =>
{
    options.AddPolicy("ApiKeyPolicy", context =>
    {
        // Extract API key for rate limiting
        var apiKey = context.Request.Headers["X-API-KEY"].FirstOrDefault();
        
        return RateLimitPartition.GetFixedWindowLimiter(
            partitionKey: apiKey ?? "anonymous",
            factory: _ => new FixedWindowRateLimiterOptions
            {
                AutoReplenishment = true,
                PermitLimit = 100,
                Window = TimeSpan.FromMinutes(1)
            });
    });
});

var app = builder.Build();

app.UseRateLimiter();
app.UseSecurityKey();

app.MapGet("/api/data", () => "Data")
   .RequireRateLimiting("ApiKeyPolicy");

OpenTelemetry Support

AspNetCore.SecurityKey emits tracing and metrics using the built-in .NET diagnostics APIs, so applications can export authentication telemetry with OpenTelemetry without adding a separate instrumentation package.

Instrumentation Names

Use these stable names when configuring OpenTelemetry:

  • ActivitySource: AspNetCore.SecurityKey
  • Meter: AspNetCore.SecurityKey

Telemetry Features

  • Authentication traces for middleware, endpoint filter, MVC filter, and authentication handler flows
  • Success and failure result tags for each authentication attempt
  • Failure reason tags for invalid API keys and authentication errors
  • Hashed API key tags for tracking key usage without exposing raw keys
  • Exception events added to activities when unexpected authentication errors occur
  • Request counter for total SecurityKey authentication attempts
  • Failure counter for failed SecurityKey authentication attempts
  • Duration histogram for authentication latency in milliseconds
  • Hashed log values: rejected API keys are logged as a SHA-256 hash, never as the raw key

Metrics

Metric Unit Description
securitykey.auth.requests {request} Number of SecurityKey authentication attempts.
securitykey.auth.failures {failure} Number of failed SecurityKey authentication attempts.
securitykey.auth.duration ms Duration of SecurityKey authentication attempts.

Tags

Tag Description
securitykey.auth.scheme Authentication scheme name when using the authentication handler.
securitykey.auth.result Authentication result, such as success or failure.
securitykey.auth.failure_reason Failure reason, such as invalid_client or authentication_error.
securitykey.auth.pattern Integration pattern, such as middleware, endpoint_filter, or mvc_filter.
securitykey.client SHA-256 hash of the API key for tracking client usage without exposing raw keys.
securitykey.endpoint Resolved endpoint display name or request path.

OpenTelemetry Configuration Example

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddSource("AspNetCore.SecurityKey")
        .AddAspNetCoreInstrumentation()
        .AddOtlpExporter())
    .WithMetrics(metrics => metrics
        .AddMeter("AspNetCore.SecurityKey")
        .AddAspNetCoreInstrumentation()
        .AddOtlpExporter());

The example assumes your application already references the OpenTelemetry packages required by the exporters and instrumentation you choose.

Best Practices

Security Considerations

  1. Use HTTPS: Always use HTTPS in production to protect API keys in transit
  2. Key Rotation: Implement regular API key rotation policies
  3. Logging: Log authentication attempts without exposing the actual keys. The library logs a SHA-256 hash of rejected keys
  4. Rate Limiting: Implement rate limiting to prevent abuse
  5. IP Restrictions: Restrict API keys to known networks with SecurityKey:AllowedNetworks when possible
  6. Timing Attack Protection: The library uses cryptographic operations to prevent timing attacks
  7. Telemetry Hygiene: Avoid recording raw API keys in custom telemetry tags or logs
  8. Forwarded Headers: Behind Cloudflare or another proxy, use UseForwardedHeaders() with the proxy as a known proxy or network in ForwardedHeadersOptions. Keep the Cloudflare ranges current. Never clear the known proxies, and keep proxy addresses out of SecurityKey:AllowedAddresses and SecurityKey:AllowedNetworks

Configuration Best Practices

  1. Environment Variables: Store sensitive keys in environment variables or secure key vaults
  2. Separate Keys: Use different API keys for different environments (dev, staging, production)
  3. Network Restrictions: Configure IP restrictions for API keys to limit access to known sources
  4. Monitor Usage: Implement logging and monitoring to track API key usage patterns

Performance Considerations

  1. Caching: Enable caching for authentication results when using custom validators
  2. Connection Pooling: Use connection pooling for database-backed validators
  3. Async Operations: Leverage async/await patterns for I/O operations
  4. Observability: Export SecurityKey traces and metrics with OpenTelemetry to monitor authentication latency and failures

Troubleshooting

Common Issues

Issue: API key not being extracted from requests

Solution: Check header/query parameter names match configuration:

builder.Services.AddSecurityKey(options =>
{
    options.HeaderName = "X-API-KEY"; // Must match client header
    options.QueryName = "apikey";     // Must match query parameter
});

Issue: Authentication works but authorization fails

Solution: Ensure authentication scheme is properly configured:

// For controller attributes
[Authorize(AuthenticationSchemes = SecurityKeyAuthenticationDefaults.AuthenticationScheme)]

// Or set as default scheme
builder.Services
    .AddAuthentication(SecurityKeyAuthenticationDefaults.AuthenticationScheme)
    .AddSecurityKey();

Issue: Custom validator not being called

Solution: Verify registration order and dependencies:

// Register dependencies first
builder.Services.AddSingleton<IApiKeyRepository, ApiKeyRepository>();
// Then register validator
builder.Services.AddSecurityKey<CustomValidator>();

Only the first registration of a validator is used. If an earlier AddSecurityKey() call already registered one, a later AddSecurityKey<CustomValidator>() does not replace it, see Provider Services and Service Keys.

Issue: Startup fails with Cannot consume scoped service '...' from singleton 'AspNetCore.SecurityKey.ISecurityKeyValidator'

Solution: AddSecurityKey<TValidator>() registers the validator as a singleton for the middleware and filters, and a singleton cannot use scoped services such as a DbContext. Registering it with AddScoped<ISecurityKeyValidator, TValidator>() fails the same way, from the singleton SecurityKeyAuthorizationFilter. Register the validator as a keyed scoped service for the authentication handler instead, see Validators with Scoped Dependencies.

Issue: IP restrictions not working correctly

Solution: The addresses belong in the SecurityKey section next to AllowedKeys, see IP Address Restrictions. Behind Cloudflare or another proxy, use the forwarded headers middleware so the real client address is used:

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.ForwardedForHeaderName = "CF-Connecting-IP";
    options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("173.245.48.0/20")); // plus all other current Cloudflare ranges
});

var app = builder.Build();
app.UseForwardedHeaders(); // Must be before UseSecurityKey(), UseAuthentication(), and UseAuthorization()

Invalid address and network entries are logged as warnings at startup, and every rejected API key is logged with the client address it was checked against.

Issue: Behind Cloudflare, IP checks see Cloudflare addresses instead of the visitor's

Solution: Use UseForwardedHeaders() with ForwardedForHeaderName = "CF-Connecting-IP" and every current Cloudflare range from cloudflare.com/ips in KnownIPNetworks (see Cloudflare). A request from a range missing from the list keeps the Cloudflare edge address. With Cloudflare Tunnel, list the cloudflared address in KnownProxies instead. Do not use ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, which trusts forwarded headers from any client.

Debug Logging

Enable detailed logging to troubleshoot issues:

{
  "Logging": {
    "LogLevel": {
      "AspNetCore.SecurityKey": "Debug",
      "Microsoft.AspNetCore.Authentication": "Debug"
    }
  }
}

Examples Repository

For complete working examples, see the samples in this repository:

Each sample includes:

  • Complete working application
  • Configuration examples
  • HTTP test files
  • Different authentication patterns

Contributing

We welcome contributions! Please see our contributing guidelines for details.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net11.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.1.0 75 12/4/2026
5.0.0 782 11/11/2026
4.3.4 695 10/13/2026
4.3.3 986 9/10/2026
4.3.2 917 8/12/2026
4.3.1 754 7/15/2026
4.3.0 6,383 5/7/2026
4.2.0 218 5/1/2026
4.1.0 2,408 2/27/2026
4.0.0 8,951 11/12/2025
3.0.0 3,929 8/16/2025
2.3.2 268 8/12/2025
2.3.1 209 8/1/2025
2.3.0 554 5/6/2025
2.2.0 266 5/6/2025
2.1.0 304 2/20/2025
2.0.1 316 12/12/2024
2.0.0 232 12/12/2024
1.2.0 233 12/11/2024
1.1.0 241 5/3/2024
Loading failed