OAuth2 & JWT
Secure API authentication with OAuth 2.0 and JSON Web Tokens.
Quick Start
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
// Login
const user = await db.user.findUnique({ where: { email } });
const valid = await bcrypt.compare(password, user.password);
if (!valid) throw new Error('Invalid credentials');
// Generate tokens
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET!,
{ expiresIn: '15m' }
);
const refreshToken = jwt.sign(
{ userId: user.id },
process.env.JWT_REFRESH_SECRET!,
{ expiresIn: '7d' }
);
// Middleware
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!);
req.user = decoded;
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}
When to Use
- API authentication and authorization
- Single sign-on (SSO) with OAuth providers
- Not for server-to-server with API keys
Step-by-Step Instructions
- Install packages:
npm install jsonwebtoken bcrypt - Set up user model with hashed passwords
- Create login endpoint returning access + refresh tokens
- Add auth middleware to protected routes
Dependencies
npm install jsonwebtoken bcrypt
# For OAuth providers: passport, passport-google-oauth20, etc.
Examples
Input: Login with email/password → Output: { accessToken, refreshToken, expiresIn }
Resources
Troubleshooting
- JWT
kidmismatch — the signing key rotated but the client cached the old JWKS. Refresh the key set and honorcache-controlon the JWKS. expclaims rejected after a clock skew — allow leeway (~30s) on verification and compare with the issuer'snbf/iat, not wall time.- Audience leaks cross-app — tokens minted for one audience validate
elsewhere. Pin
audper client and reject tokens without anaudclaim. - Refresh tokens stolen in localStorage — never store them in the browser. Use httpOnly, SameSite cookies or a backend session.
Validation
- Tokens sign and verify correctly
- Expired tokens are rejected
- Refresh tokens issue new access tokens