Expand description
API Key Authentication for Actix Web.
§Overview
API Key authentication is a simple authentication method where clients include a pre-shared key in their requests. It’s commonly used for:
- Service-to-service communication
- Public APIs with usage tracking
- Simple authentication without user sessions
§Key Locations
API keys can be extracted from:
- Header (recommended):
X-API-Key: your-api-key - Authorization header:
Authorization: ApiKey your-api-key - Query parameter:
?api_key=your-api-key(less secure)
§Usage
§Basic Setup
ⓘ
use actix_security::http::security::api_key::{
ApiKeyAuthenticator, InMemoryApiKeyRepository, ApiKeyConfig, ApiKey,
};
// Create API key repository
let mut repository = InMemoryApiKeyRepository::new();
// Add API keys
repository.add_key(ApiKey::new("sk_live_abc123")
.name("Production Key")
.roles(vec!["API_USER".into()])
.authorities(vec!["api:read".into(), "api:write".into()]));
// Create authenticator
let authenticator = ApiKeyAuthenticator::new(repository);§With Custom Header
ⓘ
let config = ApiKeyConfig::header("Authorization")
.prefix("ApiKey "); // Expects: Authorization: ApiKey sk_xxx
let authenticator = ApiKeyAuthenticator::with_config(repository, config);§Multiple Locations
ⓘ
let config = ApiKeyConfig::new()
.header("X-API-Key")
.query_param("api_key")
.authorization_scheme("ApiKey");
let authenticator = ApiKeyAuthenticator::with_config(repository, config);§Spring Security Comparison
| Spring Security | Actix Security |
|---|---|
Custom AuthenticationFilter | ApiKeyAuthenticator |
AuthenticationProvider | ApiKeyRepository |
AbstractPreAuthenticatedProcessingFilter | ApiKeyConfig locations |
§Security Considerations
- Use HTTPS - API keys are transmitted in plaintext
- Rotate keys - Implement key rotation policies
- Limit scope - Use authorities to restrict key capabilities
- Rate limit - Prevent abuse with rate limiting per key
- Audit - Log API key usage for security monitoring
§Example with Middleware
ⓘ
use actix_security::http::security::{
SecurityTransform, AuthenticationManager,
api_key::{ApiKeyAuthenticator, InMemoryApiKeyRepository, ApiKey},
};
let mut repository = InMemoryApiKeyRepository::new();
repository.add_key(ApiKey::new("sk_test_123").roles(vec!["USER".into()]));
let authenticator = ApiKeyAuthenticator::new(repository);
App::new()
.wrap(SecurityTransform::new()
.config_authenticator(move || authenticator.clone()))
.service(my_api_endpoint)Structs§
- ApiKey
- Represents an API key with associated metadata and permissions.
- ApiKey
Authenticator - Authenticator that validates API keys from requests.
- ApiKey
Builder - Builder for
ApiKey. - ApiKey
Config - Configuration for API Key authentication.
- InMemory
ApiKey Repository - In-memory implementation of
ApiKeyRepository.
Enums§
- ApiKey
Error - Errors that can occur during API key authentication.
- ApiKey
Location - Where to look for the API key in requests.
Traits§
- ApiKey
Repository - Trait for loading API keys.