Get a Pentest and security assessment of your IT network.

Cyber Security

Server to Server API Authentication

TL;DR

Secure communication between your servers using API keys and a simple authentication process. This guide covers generating keys, sending them with requests, and verifying them on the receiving server.

Generating API Keys

  1. Choose a Key Generation Method: You can use UUIDs (Universally Unique Identifiers) or more complex random string generation techniques. For simplicity, we’ll use UUIDs.
    python
    import uuid
    
    def generate_api_key():
      return str(uuid.uuid4())
    
    print(generate_api_key())
    
  2. Store Keys Securely: Never store API keys directly in your code! Use environment variables, a secrets manager (like HashiCorp Vault), or an encrypted database.

    Example using environment variables:

    # In your server's configuration:
    API_KEY=your_generated_api_key
    
  3. Associate Keys with Permissions: Link each API key to specific applications or users and define what actions they are allowed to perform. This is crucial for security.

Sending the API Key

  1. HTTP Header: The most common method is to send the API key in an HTTP header, typically named X-API-Key or Authorization. Using a dedicated header like X-API-Key is often preferred for simplicity.
    curl -H "X-API-Key: your_generated_api_key" https://your-api-endpoint
    
  2. Query Parameter (Less Secure): You can also send the key as a query parameter, but this is less secure because it’s visible in server logs and browser history.
    https://your-api-endpoint?api_key=your_generated_api_key
    

Verifying the API Key on the Server

  1. Retrieve the Key: Extract the API key from the HTTP header (or query parameter if you’re using that method).

    Example in Python Flask:

    from flask import request, jsonify
    
    @app.route('/your-api-endpoint')
    def your_api_endpoint():
      api_key = request.headers.get('X-API-Key')
      if not api_key:
        return jsonify({'message': 'API key missing'}), 401
    
  2. Validate the Key: Check if the retrieved API key exists in your secure storage and is associated with a valid application/user.

    Example (simplified):

    valid_keys = ['your_generated_api_key', 'another_valid_key']
      if api_key not in valid_keys:
        return jsonify({'message': 'Invalid API key'}), 401
    
  3. Handle Invalid Keys: Return a 401 Unauthorized status code if the key is missing or invalid. Provide a clear error message.
  4. Implement Rate Limiting: Protect your API from abuse by limiting the number of requests allowed per key within a specific time frame.

Additional Considerations

  • HTTPS: Always use HTTPS to encrypt communication between servers.
  • Key Rotation: Regularly rotate API keys to minimize the impact of compromised credentials.
  • Logging: Log key usage for auditing and security monitoring, but avoid logging the full key itself.
  • Token-Based Authentication (Advanced): For more complex scenarios, consider using token-based authentication like JWT (JSON Web Tokens) instead of API keys.
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