Blog | G5 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.

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.

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

Exit mobile version