Decode.Security.ApiKey 2.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Decode.Security.ApiKey --version 2.1.0
                    
NuGet\Install-Package Decode.Security.ApiKey -Version 2.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="Decode.Security.ApiKey" Version="2.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Decode.Security.ApiKey" Version="2.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Decode.Security.ApiKey" />
                    
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 Decode.Security.ApiKey --version 2.1.0
                    
#r "nuget: Decode.Security.ApiKey, 2.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 Decode.Security.ApiKey@2.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=Decode.Security.ApiKey&version=2.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Decode.Security.ApiKey&version=2.1.0
                    
Install as a Cake Tool

Decode.Security.ApiKey

Implementation of API Key authentication handler and service extensions for ASP.NET Core in the Decode ecosystem.

🚀 Features

  • Standard Integration: Plugs directly into ASP.NET Core's native Authentication middleware.
  • Custom Validation: Easily delegate validation logic (database, appsettings, etc.) by implementing a simple interface.
  • Flexible Claims: Bind client information or roles to the claims principal associated with the key.

📦 Installation

dotnet add package Decode.Security.ApiKey

🛠️ Setup

1. Implement your Validator

Implement IApiKeyValidator to define how keys are validated (e.g., retrieving from a database or configuration):

using System.Security.Claims;
using Decode.Security.ApiKey;

public class MyApiKeyValidator : IApiKeyValidator
{
    private readonly IConfiguration _configuration;

    public MyApiKeyValidator(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public Task<ApiKeyValidationResult> ValidateAsync(string apiKey, CancellationToken cancellationToken = default)
    {
        string? expectedKey = _configuration["ApiKey"];

        if (apiKey == expectedKey)
        {
            Claim[] claims =
            [
                new Claim(ClaimTypes.Name, "ThirdPartyIntegration"),
                new Claim(ClaimTypes.Role, "ServiceClient")
            ];
            ClaimsIdentity identity = new(claims, "ApiKey");
            ClaimsPrincipal principal = new(identity);

            return Task.FromResult(ApiKeyValidationResult.Success(principal));
        }

        return Task.FromResult(ApiKeyValidationResult.Failure());
    }
}

2. Register Services

In your Program.cs, add API Key authentication and register your custom validator:

using Decode.Security.ApiKey.Extensions;

// Register API Key authentication using your custom validator
builder.Services.AddApiKey<MyApiKeyValidator>(options =>
{
    options.HeaderName = "X-Api-Key"; // Custom header name (default is "X-Api-Key")
    options.Scheme = "ApiKey";         // Custom scheme name (default is "ApiKey")
});

builder.Services.AddAuthorization();

Default scheme (changed in 2.0.0). AddApiKey registers the scheme without claiming the application-wide default. Previously it called AddAuthentication(scheme) unconditionally, so an API that already used JWT bearer had its default silently replaced just by adding API Key support, and every existing [Authorize] endpoint started challenging with the wrong scheme.

When API Key really is the only scheme, ask for the default explicitly:

builder.Services.AddApiKey<MyApiKeyValidator>(setAsDefaultScheme: true);

To require a specific scheme per endpoint, regardless of the default:

[Authorize(AuthenticationSchemes = "ApiKey")]

3. Configure Middleware

Ensure authentication and authorization middlewares are in your pipeline:

WebApplication app = builder.Build();

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

app.MapControllers();
app.Run();

📖 Usage

Securing Controllers or Actions

Use the [Authorize] attribute with your custom scheme name:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "ApiKey")]
public class IntegrationController : ControllerBase
{
    [HttpGet]
    public IActionResult GetSecureData()
    {
        string? clientName = User.Identity?.Name;
        return Ok(new { message = $"Hello, {clientName}. You have access!" });
    }
}

📄 License

MIT License.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
3.0.0 100 9/14/2026
2.1.0 94 9/13/2026
2.0.2 90 9/13/2026
2.0.1 89 9/13/2026
2.0.0 126 7/28/2026
1.0.3 134 6/19/2026