Get a Pentest and security assessment of your IT network.

Cyber Security

API Authentication: A Simple Guide

TL;DR

This guide shows you how to securely authenticate requests between your APIs using API keys and a simple header check. It’s a common, easy-to-implement method for basic security.

1. Generate API Keys

API keys are unique strings used to identify the application making the request. They don’t prove *who* the user is, but they do prove *which app* is calling your API. You’ll need a way to generate and store these.

  • For Development: A simple script or even manual generation can work.
  • Production: Use a dedicated key management service (e.g., AWS KMS, HashiCorp Vault) for security and rotation.

Example of generating a random API Key using Python:

import uuid

def generate_api_key():
  return str(uuid.uuid4())

print(generate_api_key())

2. Store API Keys Securely

Never hardcode API keys directly into your code! This is a major security risk.

  • Client-Side: If the key needs to be used in a browser, store it securely (e.g., using environment variables or secure storage mechanisms provided by the browser).
  • Server-Side: Store keys in environment variables, configuration files (encrypted if necessary), or a dedicated secrets management system.

3. Implement Authentication on Your API Server

Your API server needs to verify the API key with each request.

  1. Extract the Key: Look for the API key in an HTTP header (e.g., X-API-Key).
  2. Validate the Key: Check if the extracted key exists in your list of valid keys.
  3. Reject Invalid Requests: If the key is missing or invalid, return a 401 Unauthorized error.

Example using Python and Flask:

from flask import Flask, request, jsonify

app = Flask(__name__)

VALID_API_KEYS = ['your_api_key_here', 'another_valid_key'] # Replace with your actual keys

def authenticate():
  api_key = request.headers.get('X-API-Key')
  if api_key in VALID_API_KEYS:
    return True
  else:
    return False

@app.route('/protected')
def protected_resource():
  if authenticate():
    return jsonify({'message': 'Access granted!'})
  else:
    return jsonify({'error': 'Unauthorized'}), 401

if __name__ == '__main__':
  app.run(debug=True)

4. Send the API Key with Requests

The client application making the request needs to include the API key in the HTTP header.

Example using curl:

curl -H "X-API-Key: your_api_key_here" https://your.api.com/protected

5. Consider Additional Security Measures

  • Rate Limiting: Prevent abuse by limiting the number of requests from a single API key within a certain timeframe.
  • HTTPS: Always use HTTPS to encrypt communication between your client and server.
  • Input Validation: Validate all input data to prevent injection attacks.
  • More Robust Authentication (OAuth 2.0, JWT): For more complex scenarios involving user authentication and authorization, consider using OAuth 2.0 or JSON Web Tokens (JWT).
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation