API Authentication
Overview
Secure API access is essential to protect data and ensure that only authorized clients can interact with your services. This guide covers the most common authentication methods, how they work, and when to use each.
API Key Authentication
An API key is a simple secret string that a client includes in each request. It’s easy to implement but provides limited security.
How to use
curl -H "X-API-Key: YOUR_API_KEY" https://api.example.com/v1/resource
OAuth 2.0
OAuth 2.0 provides a robust framework for delegated access using access tokens. It supports multiple grant types (Authorization Code, Client Credentials, etc.).
Authorization Code Flow (simplified)
// 1. Redirect user to authorization endpoint
GET https://auth.example.com/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI
// 2. Exchange code for token
POST https://auth.example.com/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=AUTH_CODE&redirect_uri=YOUR_REDIRECT_URI&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
JSON Web Token (JWT)
JWTs are signed tokens that can carry claims about the user or client. They are self‑contained and can be verified without a database lookup.
Generating a JWT (Node.js)
const jwt = require('jsonwebtoken');
const payload = {
sub: '1234567890',
name: 'John Doe',
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour
};
const token = jwt.sign(payload, process.env.JWT_SECRET, { algorithm: 'HS256' });
console.log(token);
Using the JWT
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" https://api.example.com/v1/secure-data
Best Practices
- Never embed API keys or secrets in client‑side code.
- Use HTTPS for all API calls.
- Rotate credentials regularly.
- Implement rate limiting and IP allow‑listing.
- Prefer OAuth 2.0 or JWT for public APIs.