TL;DR
Secure your two-tier application by using API keys to authenticate requests between the presentation tier (front end) and the application tier (back end). This guide shows how to generate, pass, and validate these keys.
1. Generate API Keys
The application tier should be responsible for creating unique API keys. Don’t store them in your code directly! Use a secure method like environment variables or a secrets manager.
- UUIDs: A common approach is to generate Universally Unique Identifiers (UUIDs).
python
import uuid
def generate_api_key():
return str(uuid.uuid4())
# Example usage:
api_key = generate_api_key()
print(f"New API Key: {api_key}")
2. Store API Keys Securely
Store the generated keys associated with users or applications in your database. Include metadata like creation date, expiry date (if applicable), and permissions.
- Database Table: Create a table to hold API key information. Example columns:
id,key,user_id,created_at,expires_at,permissions
3. Pass the API Key
The presentation tier needs to send the API key with every request to the application tier.
- HTTP Header: The most common and secure method is using a custom HTTP header, like
X-API-Key.
javascript
// Example using Fetch API:
fetch('/api/data', {
headers: {
'X-API-Key': 'YOUR_API_KEY'
}
})
.then(response => response.json())
.then(data => console.log(data));
4. Validate the API Key
The application tier must validate the X-API-Key header on every incoming request.
- Middleware: Implement middleware to intercept requests and check for a valid key.
python
# Example using Flask:
from flask import Flask, request, jsonify
def validate_api_key(f):
def decorated_function(*args, **kwargs):
api_key = request.headers.get('X-API-Key')
if not api_key:
return jsonify({'message': 'API key missing'}), 401
# Check if the API key exists in your database.
# Replace with your actual database query logic.
valid_key = check_api_key_in_database(api_key)
if not valid_key:
return jsonify({'message': 'Invalid API key'}), 401
return f(*args, **kwargs)
return decorated_function
5. Error Handling
Implement proper error handling for invalid or missing API keys.
- HTTP Status Codes: Use appropriate HTTP status codes like
401 Unauthorizedfor invalid keys and403 Forbiddenif the key lacks sufficient permissions.
6. Key Rotation (Optional)
Regularly rotate API keys to enhance security.
- Automated Process: Implement a process to automatically generate new keys and invalidate old ones.

