What Is OAuth 2.0 & JWT? Modern Authentication Guide
You click "Sign in with Google" every day. But what happens behind the scenes? Learn how OAuth 2.0 and JWT power modern authentication.
Authentication vs Authorization
| Concept | Question | Example | |---------|----------|---------| | Authentication | Prove who you are | Login (username + password) | | Authorization | Check what you can do | Admin or regular user? |
What Is JWT?
JWT (JSON Web Token) is a compact token format for securely transmitting information between parties. It has three parts:
eyJhbGciOi... . eyJzdWIiOi... . SflKxwRJSM...
Header Payload Signature
Payload Example
{
"sub": "user-42",
"name": "Ali",
"role": "admin",
"iat": 1708000000,
"exp": 1708003600
}
Creating JWTs (Node.js)
const jwt = require('jsonwebtoken');
// Create
const token = jwt.sign(
{ userId: 42, role: 'admin' },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Verify
const decoded = jwt.verify(token, process.env.JWT_SECRET);
Auth Middleware
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Token required' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}
What Is OAuth 2.0?
OAuth 2.0 is an authorization protocol that lets an application access resources on behalf of a user without exposing their credentials.
Authorization Code Flow
1. User clicks "Sign in with Google"
2. App redirects to Google
3. User logs in, grants permission
4. Google returns authorization code
5. App exchanges code for access token
6. App uses token to access Google APIs
OAuth 2.0 Roles
| Role | Description | |------|-------------| | Resource Owner | The user | | Client | Your application | | Authorization Server | Google, GitHub (issues tokens) | | Resource Server | Protected API |
Token Types
| Token | Lifetime | Purpose | |-------|----------|---------| | Access Token | 15-60 min | API requests | | Refresh Token | 7-30 days | Get new access tokens | | ID Token | 15-60 min | User info (OpenID Connect) |
Security Best Practices
- Store tokens in HttpOnly cookies — Protection against XSS
- Short-lived access tokens — 15-60 minutes
- Token rotation — Issue new refresh tokens on each refresh
- Require HTTPS — Tokens must be encrypted in transit
- No sensitive data in payload — JWT can be decoded
- Use PKCE — Extra security for SPAs and mobile apps
Session vs JWT
| Feature | Session | JWT | |---------|---------|-----| | Storage | Server (Redis) | Client | | Scalability | Requires shared state | Stateless | | Revocation | Easy (delete) | Hard (needs blacklist) |
Conclusion
OAuth 2.0 and JWT form the authentication backbone of modern web applications. JWT provides stateless tokens, while OAuth offers a standard protocol for third-party integration. Together, they enable secure, scalable auth systems.
Learn security and authentication on LabLudus.