The Difference Between Authentication and Authorization
First, let’s clarify two concepts that are often confused.
- Authentication: “Who are you?” - Verifying a user’s identity
- Authorization: “What can you do?” - Verifying access permissions
flowchart LR
Login["Login"] -->|Authentication| Auth["Verify identity with ID/Password"]
Auth --> Action["Action"]
Action -->|Authorization| Perm["Check if user has permission for this action"]
Comparison of Authentication Methods
| Method | State Management | Suitable Cases |
|---|
| Session Authentication | Server-side | Traditional web apps |
| Token Authentication (JWT) | Client-side | SPA, mobile apps |
| OAuth 2.0 | External service | Third-party auth, API integration |
Session Authentication
How It Works
sequenceDiagram
participant Client
participant Server
Note over Client, Server: 1. Login
Client->>Server: Send ID/Password
Server->>Server: Authenticate → Generate Session ID → Store in session store
Server->>Client: Set-Cookie: session_id=abc123
Note over Client, Server: 2. Subsequent Requests
Client->>Server: Cookie: session_id=abc123
Server->>Server: Validate Session ID in session store
Implementation Example
const session = require('express-session');
const RedisStore = require('connect-redis').default;
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000
}
}));
app.post('/login', async (req, res) => {
const user = await authenticate(req.body);
if (user) {
req.session.userId = user.id;
res.json({ success: true });
}
});
Pros and Cons
| Pros | Cons |
|---|
| Easy to invalidate sessions | Requires server-side state management |
| Easy security control | Need session sharing in distributed environments |
| Simple implementation | Poor compatibility with mobile apps |
Token Authentication (JWT)
How It Works
sequenceDiagram
participant Client
participant Server
Note over Client, Server: 1. Login
Client->>Server: Send ID/Password
Server->>Server: Authenticate → Generate JWT (with signature)
Server->>Client: { "token": "eyJhbG..." }
Note over Client, Server: 2. Subsequent Requests
Client->>Server: Authorization: Bearer eyJhbG...
Server->>Server: Validate JWT signature (no store access needed)
JWT Structure
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. ← Header
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6... ← Payload
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ← Signature
Header (Base64 decoded):
{ "alg": "HS256", "typ": "JWT" }
Payload (Base64 decoded):
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516325422
}
Implementation Example
const jwt = require('jsonwebtoken');
app.post('/login', async (req, res) => {
const user = await authenticate(req.body);
if (user) {
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });
}
});
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 (error) {
res.status(401).json({ error: 'Invalid token' });
}
}
Refresh Tokens
| Token Type | Lifespan | Storage |
|---|
| Access Token | Short-lived (15 min - 1 hour) | Memory/localStorage |
| Refresh Token | Long-lived (7 - 30 days) | Stored securely |
Flow:
- Access Token expires
- Get new Access Token using Refresh Token
- Refresh Token also expires → Re-login required
Pros and Cons
| Pros | Cons |
|---|
| Stateless, easy to scale | Difficult to invalidate tokens |
| Suitable for distributed systems | Large token size |
| Suitable for mobile/SPA | Payload is not encrypted |
OAuth 2.0
Overview
A mechanism for authentication and authorization using third-party services (Google, GitHub, etc.).
sequenceDiagram
participant User
participant App as Your App (Client)
participant Auth as Auth Server (Google, etc.)
User->>App: 1. Click Login Button
App->>Auth: 2. Auth Request
Auth->>User: 3. Login Screen
User->>Auth: 4. Authenticate & Consent
Auth->>App: 5. Auth Code
App->>Auth: 6. Token Request
Auth->>App: 7. Access Token
App->>User: 8. Login Complete
Implementation Example (Authorization Code Flow)
app.get('/auth/google', (req, res) => {
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
authUrl.searchParams.set('client_id', process.env.GOOGLE_CLIENT_ID);
authUrl.searchParams.set('redirect_uri', 'https://myapp.com/callback');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid email profile');
authUrl.searchParams.set('state', generateState());
res.redirect(authUrl.toString());
});
app.get('/callback', async (req, res) => {
const { code, state } = req.query;
verifyState(state);
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
body: new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
code,
grant_type: 'authorization_code',
redirect_uri: 'https://myapp.com/callback'
})
});
const { access_token, id_token } = await tokenResponse.json();
});
Grant Types
| Grant Type | Use Case |
|---|
| Authorization Code | Web apps (most common) |
| PKCE | SPA, mobile apps |
| Client Credentials | Server-to-server communication |
| Device Code | Smart TV and input-limited devices |
Choosing an Authentication Method
| Application Type | Recommended Method |
|---|
| Traditional Web App (Server-Side Rendering) | Session Authentication |
| SPA + API | JWT (Short-lived Access Token + Refresh Token) |
| Mobile App | JWT or OAuth 2.0 (PKCE) |
| Third-party Login (Login with Google, etc.) | OAuth 2.0 / OpenID Connect |
| Microservice-to-Microservice Communication | JWT or OAuth 2.0 (Client Credentials) |
Summary
The choice of authentication method depends on the type of application, security requirements, and scalability requirements. Session authentication is simple to implement and easy to control, while JWT is stateless and easy to scale. OAuth 2.0 is optimal for third-party authentication and API integration. Understand the characteristics of each method and choose the appropriate one for your use case.
← Back to list