DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

API Authentication Methods

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

API Authentication Methods

Introduction

API authentication verifies the identity of clients calling your API. Choosing the right authentication method depends on the threat model, client type, and operational requirements. This guide covers the four dominant approaches and their appropriate use cases.

API Keys

API keys are the simplest form of API authentication. A static token is issued to each client and included in every request.

from fastapi import FastAPI, HTTPException, Depends

from fastapi.security import APIKeyHeader

app = FastAPI()

api_key_header = APIKeyHeader(name="X-API-Key")

API_KEYS = {

"sk-live-a1b2c3d4": {"client": "payment-service", "scopes": ["read:transactions"]},

"sk-test-e5f6g7h8": {"client": "test-client", "scopes": ["read:test"]},

}

def validate_api_key(api_key: str = Depends(api_key_header)):

if api_key not in API_KEYS:

raise HTTPException(status_code=403, detail="Invalid API key")

return API_KEYS[api_key]

@app.get("/api/transactions")

def get_transactions(client=Depends(validate_api_key)):

if "read:transactions" not in client["scopes"]:

raise HTTPException(status_code=403, detail="Insufficient permissions")

return {"transactions": [...]}

Pros: Simple, fast, easy to revoke. Cons: Static keys can leak, no identity delegation, limited granularity.

OAuth2 Client Credentials

The OAuth2 client credentials grant is designed for server-to-server communication where the client is the resource owner.

import requests

from authlib.integrations.requests_client import OAuth2Session

Client configuration

client = OAuth2Session(

client_id='my-service',

client_secret='my-secret',

scope='read:orders write:orders'

)

Obtain access token

token = client.fetch_token(

url='https://auth.example.com/oauth/token',

grant_type='client_credentials'

)

Use token for API


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)