A simple API Key authentication library for ASP.NET Core
$ dotnet add package Edi.AspNetCore.ApiKeyAuthA simple and flexible API Key authentication library for ASP.NET Core applications.
appsettings.jsonsequenceDiagram
participant Client
participant API
participant Handler
participant Validator
participant Config
Client->>API: HTTP Request with Raw API Key
API->>Handler: Extract raw key from request
Handler->>Validator: ValidateApiKeyAsync(rawKey)
Validator->>Config: Get stored hashed keys
Validator->>Validator: Hash raw key and compare
Validator->>Handler: Return validation result
Handler->>API: Authentication success/failure
API->>Client: Response
Install the package via NuGet:
dotnet add package Edi.AspNetCore.ApiKeyAuth
Or via Package Manager Console:
Install-Package Edi.AspNetCore.ApiKeyAuth
Add your API keys to appsettings.json:
{
"ApiKeys": [
{
"Identifier": "MyApp",
"Key": "your-plain-text-key", // Legacy support
"HashedKey": "base64-encoded-hashed-key", // Preferred
"Roles": ["Admin", "User"],
"Scopes": ["read", "write", "delete"],
"ExpiresAt": "2025-12-31T23:59:59Z",
"IsActive": true,
"Description": "Primary application API key",
"RateLimit": {
"RequestsPerMinute": 100,
"RequestsPerHour": 5000,
"RequestsPerDay": 50000
},
"IpWhitelist": {
"Enabled": true,
"AllowedIpAddresses": ["192.168.1.100"],
"AllowedCidrRanges": ["10.0.0.0/8", "192.168.0.0/16"]
}
}
]
}
In your Program.cs or Startup.cs:
using Edi.AspNetCore.ApiKeyAuth;
var builder = WebApplication.CreateBuilder(args);
// Add API Key authentication
builder.Services.AddApiKeyAuthentication(options =>
{
options.AllowQueryStringAuth = false; // Disable for security
options.EnableDetailedLogging = builder.Environment.IsDevelopment();
options.EnableCaching = true;
});
var app = builder.Build();
// Enable authentication and authorization
app.UseAuthentication();
app.UseAuthorization();
app.Run();
Use the [Authorize] attribute on controllers or actions:
[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "ApiKey")]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult GetData()
{
// Access enhanced claims
var userIdentifier = User.FindFirst("UserIdentifier")?.Value;
var roles = User.FindAll(ClaimTypes.Role).Select(c => c.Value).ToArray();
var scopes = User.FindAll("scope").Select(c => c.Value).ToArray();
return Ok(new
{
User = userIdentifier,
Roles = roles,
Scopes = scopes,
Message = "Hello from secure endpoint!"
});
}
[HttpPost]
[Authorize(Roles = "Admin")] // Role-based authorization
public IActionResult AdminOnly()
{
return Ok("Admin access granted");
}
}