API Key
A secure API Key Management system for ASP.NET Core applications, built with Clean Architecture principles. Provides key generation, validation, rotation, permission-based access control, and full CRUD operations.
๐ Overviewโ
The API Key Management module enables secure API access using keys linked to users and permission IDs. It supports key creation, validation, rotation, revocation, and permission assignment.
๐ Dependency Graphโ
โจ Key Featuresโ
- Secure API key generation and validation
- Permission-based access control (scopes are permission IDs)
- Key rotation and revocation
- Full CRUD for API keys and scopes
- Clean Architecture and async/await support
- FluentValidation for request validation
- Entity Framework Core integration
- Comprehensive unit test coverage
๐ฆ Installationโ
Add the following packages to your project:
<PackageReference Include="MasLazu.AspNet.ApiKey.Abstraction" Version="1.0.0" />
<PackageReference Include="MasLazu.AspNet.ApiKey.Domain" Version="1.0.0" />
<PackageReference Include="MasLazu.AspNet.ApiKey" Version="1.0.0" />
<PackageReference Include="MasLazu.AspNet.ApiKey.EfCore" Version="1.0.0" />
<PackageReference Include="MasLazu.AspNet.ApiKey.Endpoint" Version="1.0.0" />
Service Registrationโ
// Register API key services
builder.Services.AddApiKeyApplication();
// Register EF Core DbContext
builder.Services.AddDbContext<ApiKeyDbContext>(options =>
options.UseSqlServer(connectionString));
// Register endpoints (if using Endpoint project)
builder.Services.AddFastEndpoints();
๐๏ธ Core Conceptsโ
Entitiesโ
ApiKeyโ
public class ApiKey : BaseEntity
{
public Guid UserId { get; set; }
public string Key { get; set; } = string.Empty;
public string? Name { get; set; }
public DateTime? ExpiresDate { get; set; }
public DateTime? LastUsed { get; set; }
public DateTime? RevokedDate { get; set; }
public ICollection<ApiKeyScope> Scopes { get; set; } = [];
}
ApiKeyScopeโ
public class ApiKeyScope : BaseEntity
{
public Guid ApiKeyId { get; set; }
public Guid PermissionId { get; set; }
public ApiKey? ApiKey { get; set; }
}
Data Transfer Objectsโ
ApiKeyDtoโ
public record ApiKeyDto(
Guid Id,
Guid UserId,
string Key,
string? Name,
DateTimeOffset? ExpiresDate,
DateTimeOffset? LastUsed,
DateTimeOffset? RevokedDate,
DateTimeOffset CreatedAt,
DateTimeOffset? UpdatedAt
);
CreateApiKeyRequestโ
public record CreateApiKeyRequest(
Guid UserId,
string? Name,
DateTime? ExpiresDate
);
๐ ๏ธ API Referenceโ
API Key Endpointsโ
POST /apikeys
- Create API keyGET /apikeys
- List API keys (paginated)GET /apikeys/{id}
- Get API key by IDPUT /apikeys/{id}
- Update API keyDELETE /apikeys/{id}
- Delete API keyPOST /apikeys/{id}/revoke
- Revoke API keyPOST /apikeys/{id}/rotate
- Rotate API keyPOST /apikeys/validate
- Validate API keyGET /apikeys/user/{userId}
- Get all API keys for a userPOST /apikeys/revoke-all/{userId}
- Revoke all API keys for a user
API Key Scope Endpointsโ
POST /apikeys/scopes
- Add scopeGET /apikeys/scopes
- List scopes (paginated)GET /apikeys/scopes/{id}
- Get scope by IDPUT /apikeys/scopes/{id}
- Update scopeDELETE /apikeys/scopes/{id}
- Delete scope
Example: Create API Keyโ
POST /apikeys
Content-Type: application/json
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"name": "My API Key",
"expiresDate": "2025-12-31T23:59:59Z"
}
Response:
{
"id": "...",
"userId": "...",
"key": "...",
"name": "My API Key",
"expiresDate": "2025-12-31T23:59:59Z",
"lastUsed": null,
"revokedDate": null,
"createdAt": "...",
"updatedAt": null
}
Example: Validate API Keyโ
POST /apikeys/validate
Content-Type: application/json
{
"key": "...",
"permissionId": "..." // optional
}
Response:
true
๐ป Usage Exampleโ
// Inject the API key service
private readonly IApiKeyService _apiKeyService;
// Create API key
var request = new CreateApiKeyRequest(userId, "My API Key", DateTime.UtcNow.AddDays(30));
var apiKey = await _apiKeyService.CreateAsync(userId, request);
// Validate API key
var isValid = await _apiKeyService.ValidateAsync(new ValidateApiKeyRequest("api-key", permissionId));
// Rotate API key
var rotatedKey = await _apiKeyService.RotateAsync(userId, apiKey.Id);
๐ง Configurationโ
Database Migrationโ
# Add migration
dotnet ef migrations add InitialCreate --project src/MasLazu.AspNet.ApiKey.EfCore
# Update database
dotnet ef database update --project src/MasLazu.AspNet.ApiKey.EfCore
Appsettings.jsonโ
{
"ConnectionStrings": {
"ApiKeyDb": "Server=.;Database=ApiKeyDb;Trusted_Connection=True;"
}
}
๐๏ธ Project Structureโ
src/
โโโ MasLazu.AspNet.ApiKey.Abstraction/
โ โโโ Interfaces/ # Service interfaces
โ โโโ Models/ # DTOs and request/response models
โโโ MasLazu.AspNet.ApiKey.Domain/
โ โโโ Entities/ # Domain entities (ApiKey, ApiKeyScope)
โโโ MasLazu.AspNet.ApiKey/
โ โโโ Extensions/ # Service registration extensions
โ โโโ Services/ # Business logic implementations
โ โโโ Validators/ # FluentValidation validators
โโโ MasLazu.AspNet.ApiKey.EfCore/
โ โโโ Configurations/ # Entity configurations
โ โโโ Data/ # DbContext and repositories
โ โโโ Extensions/ # EF Core service registration
โโโ MasLazu.AspNet.ApiKey.Endpoint/
โโโ EndpointGroups/ # Endpoint grouping
โโโ Endpoints/ # FastEndpoints implementations
โโโ Extensions/ # Endpoint registration
test/
โโโ MasLazu.AspNet.ApiKey.Test/
โโโ MasLazu.AspNet.ApiKey.EfCore.Test/
โโโ MasLazu.AspNet.ApiKey.Endpoint.Test/
๐งช Testingโ
Run the test suite:
dotnet test test/MasLazu.AspNet.ApiKey.Test/
๐ Security Featuresโ
- Secure key generation (GUID-based)
- Key validation with expiration and revocation
- Permission-based access control (permission IDs)
- FluentValidation for all requests
- Audit trail with timestamps
๐ Related Documentationโ
๐ค Contributingโ
Contributions are welcome! Please ensure:
- All tests pass
- Code follows the established patterns
- Documentation is updated
- Security best practices are followed
- FluentValidation rules are comprehensive
๐ Licenseโ
This project is licensed under the MIT License - see the LICENSE file for details.