API Authentication Methods

API authentication strategies and implementation.

API Keys

In header
X-API-Key: your-api-key-here
Authorization: ApiKey your-api-key

In query parameter
GET /api/users?api_key=your-api-key

Node.js validation
app.use((req, res, next) => {
  const apiKey = req.headers["x-api-key"];
  if (apiKey !== process.env.API_KEY) {
    return res.status(401).json({ error: "Invalid API key" });
  }
  next();
});

Bearer Token (JWT)

Authorization header
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Node.js validation
const jwt = require("jsonwebtoken");

app.use((req, res, next) => {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) {
    return res.status(401).json({ error: "No token" });
  }
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: "Invalid token" });
  }
});

Basic Authentication

Header format
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Base64 encoded username:password

Create header (JavaScript)
const credentials = btoa("username:password");
const headers = {
  Authorization: `Basic ${credentials}`
};

Node.js validation
app.use((req, res, next) => {
  const auth = req.headers.authorization;
  if (!auth?.startsWith("Basic ")) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  const credentials = Buffer.from(auth.slice(6), "base64").toString();
  const [username, password] = credentials.split(":");
  // Validate username and password
});

OAuth 2.0

Access token request
POST /oauth/token
Body:
{
  "grant_type": "authorization_code",
  "code": "AUTH_CODE",
  "client_id": "CLIENT_ID",
  "client_secret": "CLIENT_SECRET"
}

Use access token
Authorization: Bearer ACCESS_TOKEN

Refresh token
POST /oauth/token
{
  "grant_type": "refresh_token",
  "refresh_token": "REFRESH_TOKEN"
}