API Key authentication
API Key authentication is a simple authentication method where clients pass a secret key as part of their request, typically in a header. This key serves as both the identifier and the authentication mechanism.
Ktor allows you to use API Key authentication for securing routes and validating client requests.
Add dependencies
To enable API Key authentication, add the ktor-server-auth and ktor-server-auth-api-key artifacts in the build script:
API Key authentication flow
The API Key authentication flow looks as follows:
A client makes a request with an API key included in a header (typically
X-API-Key) to a specific route in a server application.The server validates the API key using custom validation logic.
If the key is valid, the server responds with the requested content. If the key is invalid or missing, the server responds with a
401 Unauthorizedstatus.
Install API Key authentication
To install the apiKey authentication provider, call the apiKey function inside the install(Authentication) block:
You can optionally specify a provider name that can be used to authenticate a specified route.
Configure API Key authentication
In this section, we'll see the configuration specifics of the apiKey authentication provider.
Step 1: Configure an API Key provider
The apiKey authentication provider exposes its settings via the ApiKeyAuthenticationProvider.Config class. In the example below, the following settings are specified:
The
validatefunction receives the API key extracted from the request and returns aPrincipalin the case of successful authentication ornullif authentication fails.
Here's a minimal example:
Customize key location
By default, the apiKey provider looks for the API key in the X-API-Key header.
You can use headerName to specify a custom header:
Step 2: Validate API keys
The validation logic depends on your application's requirements. Here are common approaches:
Static key comparison
For simple cases, you can compare against a predefined key:
Database lookup
For multiple API keys, validate against a database:
Multiple validation criteria
You can implement complex validation logic:
Step 3: Configure challenge
You can customize the response sent when authentication fails using the challenge function:
Step 4: Protect specific resources
After configuring the apiKey provider, you can protect specific resources in your application using the authenticate function. In the case of successful authentication, you can retrieve an authenticated principal inside a route handler using the call.principal function.
API Key authentication example
Here's a complete minimal example of API Key authentication:
Best practices
When implementing API Key authentication, consider the following best practices:
Use HTTPS: Always transmit API keys over HTTPS to prevent interception.
Store securely: Never hardcode API keys in source code. Use environment variables or secure configuration management.
Key rotation: Implement a mechanism for rotating API keys periodically.
Rate limiting: Combine API Key authentication with rate limiting to prevent abuse.
Logging: Log authentication failures for security monitoring, but never log the actual API keys.
Key format: Use cryptographically secure random strings for API keys (for example, UUID or base64-encoded random bytes).
Multiple keys: Consider supporting multiple API keys per user for different applications or purposes.
Expiration: Implement key expiration for enhanced security.