Authentication & Authorization

Securely authenticate users with OAuth2, JWT, and API keys

This guide covers secure authentication patterns including JSON Web Tokens (JWT), OAuth2 flows, API token authentication, and rate limiting best practices for modern web applications.

🛡

JWT Implementation

Use JSON Web Tokens for stateless authentication between clients and services

npm install jsonwebtoken bcrypt
🔐

OAuth2.0

Implement secure delegated authentication with social and enterprise providers

github / google / microsoft
🔑

API Keys

Rate-limited access control for machine-to-machine communication

X-API-KEY header

Implementation Guide

JWT Workflow

  • • User signs in with credentials
  • • Server validates credentials
  • • Generate signed JWT token
  • • Client stores token in secure HTTP-only cookie
  • • Subsequent requests use Bearer token authentication

OAuth2 Flow

  • • Redirect user to provider authorization endpoint
  • • Provider returns verification code
  • • Exchange code for access token
  • • Store refresh token securely
  • • Implement token rotation and revocation

Code Examples

server.js
const jwt = require('jsonwebtoken');
app.post('/login', async (req, res) => {
    // Validate credentials
    const token = jwt.sign({ userId: user.id }, process.env.SECRET, {
        expiresIn: '24h'
    });
    res.cookie('token', token, { httpOnly: true });
});
                        
middleware.js
export const requireKey = (req, res, next) => {
    const key = req.headers['x-api-key'];
    if (!key || !validKeys.includes(key)) {
        return res.status(401).end();
    }
    next();
};
                        

Security Checklist

Use HTTPS for all communication
Rotate secrets regularly
! Implement proper refresh token invalidation
📘 Follow OWASP API Top 10 guidelines