Skip to main content

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 key
  • GET /apikeys - List API keys (paginated)
  • GET /apikeys/{id} - Get API key by ID
  • PUT /apikeys/{id} - Update API key
  • DELETE /apikeys/{id} - Delete API key
  • POST /apikeys/{id}/revoke - Revoke API key
  • POST /apikeys/{id}/rotate - Rotate API key
  • POST /apikeys/validate - Validate API key
  • GET /apikeys/user/{userId} - Get all API keys for a user
  • POST /apikeys/revoke-all/{userId} - Revoke all API keys for a user

API Key Scope Endpointsโ€‹

  • POST /apikeys/scopes - Add scope
  • GET /apikeys/scopes - List scopes (paginated)
  • GET /apikeys/scopes/{id} - Get scope by ID
  • PUT /apikeys/scopes/{id} - Update scope
  • DELETE /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

๐Ÿค Contributingโ€‹

Contributions are welcome! Please ensure:

  1. All tests pass
  2. Code follows the established patterns
  3. Documentation is updated
  4. Security best practices are followed
  5. FluentValidation rules are comprehensive

๐Ÿ“„ Licenseโ€‹

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