Blog | G5 Cyber Security

API Key Authentication

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.

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.

3. Pass the API Key

The presentation tier needs to send the API key with every request to the application tier.

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.

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.

6. Key Rotation (Optional)

Regularly rotate API keys to enhance security.

Exit mobile version