
Login, JWT, OAuth2, refresh token, logoutLogin, JWT, OAuth2, refresh tokens, logout
Chín giờ săn saleThe nine o'clock sale.Hãy theo chân Lan vào đợt sale 9 giờ của một sàn Việt có 500.000 người dùng mỗi tháng. Lan đăng nhập để xem đơn và giữ nhịp mua sắm khi phiên cần gia hạn.Follow Lan into the 9 AM sale at a Vietnamese marketplace with 500,000 monthly users. She signs in to view her orders and keep shopping as her session needs renewal.
Hãy theo yêu cầu của Lan từ lúc đăng nhập trước giờ sale đến khi xem đơn qua Order API: trình duyệt đi qua BFF, mật khẩu chỉ được kiểm lúc đăng nhập, còn JWT được kiểm ngay tại API. BFF đặt refresh token trong cookie HttpOnly để JavaScript không đọc được, trong khi Auth Service giữ bản băm để xoay và thu hồi phiên. Chọn hai tình huống tiếp theo để thấy phiên được gia hạn lúc 9:15 và cách hệ thống phản ứng khi token cũ xuất hiện lần nữa.Follow Lan's request from signing in before the sale to viewing orders through Order API: the browser goes through the BFF, passwords are checked at login, and JWTs are verified at the API. The BFF sets an HttpOnly refresh-token cookie that JavaScript cannot read, while Auth Service keeps a hash for rotation and revocation. Select the next two scenarios to see renewal at 9:15 and what happens when an old token appears again.
1Người dùng nhập email và mật khẩu trên trang đăng nhập.The user enters an email and password on the sign-in page.
Dùng bcrypt (cost 12) hoặc argon2id (m=64 MB, t=3), mỗi mật khẩu có salt riêng sẵn trong hash. Không dùng SHA-256 thuần vì GPU thử hàng tỷ lần mỗi giây. Lưu chuỗi hash có cả thuật toán và tham số để nâng cost dần khi người dùng đăng nhập lại.Use bcrypt (cost 12) or argon2id (m=64 MB, t=3); each hash carries its own salt. Plain SHA-256 is wrong because a GPU tries billions per second. Store the full hash string with algorithm and parameters so you can raise the cost on the next successful login.
Đếm lần sai trong Redis theo email (5 lần / 15 phút) và theo IP (20 lần / 15 phút). Quá ngưỡng thì trì hoãn tăng dần hoặc đòi CAPTCHA thay vì khoá cứng tài khoản, để kẻ xấu không khoá được người khác. Báo lỗi chung “Email hoặc mật khẩu không đúng” và vẫn chạy bcrypt với hash giả khi email không tồn tại để không lộ qua thời gian phản hồi.Count failures in Redis per email (5 per 15 minutes) and per IP (20 per 15 minutes). Past the limit add a growing delay or a CAPTCHA rather than a hard lock, so attackers cannot lock other people out. Return one generic “wrong email or password” message and still run bcrypt against a dummy hash when the email does not exist, so response time leaks nothing.
JWT hợp lệ tới khi hết exp. Giữ access token ngắn (5–15 phút) và để refresh token, vốn có trạng thái trong DB, làm điểm thu hồi. Trường hợp khẩn cấp thì thêm deny list theo jti trong Redis với TTL bằng thời gian còn lại của token.A JWT stays valid until exp. Keep access tokens short (5–15 minutes) and let the refresh token, which has state in the DB, be the revocation point. For emergencies add a deny list by jti in Redis with a TTL equal to the token's remaining life.
Xoay vòng mỗi lần dùng: token cũ chuyển ROTATED, token mới cùng family. Token ROTATED mà xuất hiện lại thì thu hồi cả family và báo người dùng. Chỉ lưu SHA-256 của token để lộ DB không lộ token.Rotate on every use: the old token becomes ROTATED and the new one joins the same family. If a ROTATED token shows up again, revoke the family and warn the user. Store only the SHA-256 of the token so a leaked DB does not leak tokens.
Không để refresh token trong localStorage. BFF giữ nó trong cookie HttpOnly, Secure, SameSite=Strict, Path=/auth/refresh, kèm CSRF token cho các yêu cầu đổi trạng thái. Access token chỉ ở bộ nhớ của tab.Never put the refresh token in localStorage. The BFF keeps it in an HttpOnly, Secure, SameSite=Strict cookie with Path=/auth/refresh, plus a CSRF token for state-changing requests. The access token lives only in the tab's memory.
Một chuỗi filter: lấy Bearer token → kiểm tra chữ ký với JWKS (cache theo kid) → kiểm tra iss, aud, exp → nạp quyền vào context. Spring Security SecurityFilterChain hay middleware Go đều là Chain of Responsibility; logging và metric bọc ngoài như decorator.A chain of filters: extract the Bearer token → verify the signature against the JWKS (cached by kid) → check iss, aud, exp → put the principal in the context. Spring Security's SecurityFilterChain and Go middleware are both a Chain of Responsibility; logging and metrics wrap it as decorators.
Dùng Authorization Code + PKCE. BFF là confidential client: đổi code lấy token ở phía server, kiểm tra state, nonce và chữ ký id_token, rồi phát phiên riêng của hệ thống. Trình duyệt không bao giờ thấy token của IdP. Mỗi IdP là một strategy cấu hình riêng.Use the Authorization Code flow with PKCE. The BFF is a confidential client: it exchanges the code server-side, checks state, nonce and the id_token signature, then issues the system's own session. The browser never sees the IdP's tokens. Each IdP is a separately configured strategy.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
app_user | id, email, password_hash, password_changed_at, status, mfa_enabled, created_at | unique(lower(email)); password_hash dạng $2b$12$… hoặc $argon2id$v=19$…unique(lower(email)); password_hash looks like $2b$12$… or $argon2id$v=19$… |
refresh_token | id, user_id, token_hash, family_id, parent_id, status, expires_at, created_at, revoked_reason | unique(token_hash); ACTIVE → ROTATED · REVOKED; index(family_id) để thu hồi cả familyunique(token_hash); ACTIVE → ROTATED · REVOKED; index(family_id) to revoke a family |
user_identity | user_id, provider, subject, email, linked_at | PK(provider, subject): liên kết tài khoản Google/Microsoft với user nội bộPK(provider, subject): links a Google/Microsoft account to the local user |
Redis login:fail:{email} · login:fail:ip:{ip} | INCR counter, EXPIRE 900 | Cửa sổ 15 phút; đăng nhập đúng thì DEL bộ đếm theo email15-minute window; a successful login deletes the per-email counter |
signing_key | kid, public_jwk, private_key_ref, status, created_at | Xoay khoá ký mỗi quý; JWKS công bố cả khoá cũ tới khi token cũ hết hạnRotate the signing key every quarter; the JWKS keeps the old key until its tokens expire |
RefreshTokenService (Java) và RefreshService (Go) là hộp Auth Service ở sơ đồ, được BFF gọi ở /auth/refresh; RefreshTokenRepository đọc ghi bảng refresh_token trong hộp Postgres, còn TokenReuseDetected đi sang hộp Security Events. Điểm khó: khi phát hiện dùng lại, việc thu hồi phải được commit dù hàm trả lỗi cho client.RefreshTokenService (Java) and RefreshService (Go) are the Auth Service box in the diagram, called by the BFF on /auth/refresh; RefreshTokenRepository reads and writes refresh_token in the Postgres box, and TokenReuseDetected goes to the Security Events box. The tricky part: when reuse is detected, the revocation must commit even though the call returns an error to the client.
package com.shop.auth;
import static com.shop.auth.TokenHashing.sha256;
import com.shop.auth.RefreshToken.Status;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class RefreshTokenService {
private static final Duration ACCESS_TTL = Duration.ofMinutes(15);
private static final Duration REFRESH_TTL = Duration.ofDays(30);
private final RefreshTokenRepository repo;
private final JwtIssuer jwt;
private final ApplicationEventPublisher events;
private final SecureRandom random = new SecureRandom();
@Transactional(noRollbackFor = InvalidTokenException.class)
public TokenPair rotate(String raw) {
RefreshToken old = repo.findByHashForUpdate(sha256(raw))
.orElseThrow(InvalidTokenException::new);
if (old.getStatus() != Status.ACTIVE) {
repo.revokeFamily(old.getFamilyId(), "reuse");
events.publishEvent(new TokenReuseDetected(old.getUserId(), old.getFamilyId()));
throw new InvalidTokenException();
}
if (old.getExpiresAt().isBefore(Instant.now())) throw new InvalidTokenException();
old.setStatus(Status.ROTATED);
String next = newToken();
repo.save(RefreshToken.childOf(old, sha256(next), Instant.now().plus(REFRESH_TTL)));
return new TokenPair(jwt.issue(old.getUserId(), ACCESS_TTL), next);
}
private String newToken() {
byte[] b = new byte[32];
random.nextBytes(b);
return Base64.getUrlEncoder().withoutPadding().encodeToString(b);
}
}package main
import (
"context"
"crypto/rand"
"encoding/base64"
"time"
)
type RefreshService struct {
tx TxRunner
jwt JWTIssuer
events Publisher
}
func (s *RefreshService) Rotate(ctx context.Context, raw string) (TokenPair, error) {
var pair TokenPair
var reused *RefreshToken
err := s.tx.Do(ctx, func(tx Tx) error {
old, err := tx.LockRefreshByHash(ctx, sha256Hex(raw)) // FOR UPDATE
if err != nil {
return ErrInvalidToken
}
if old.Status != StatusActive {
reused = old
return tx.RevokeFamily(ctx, old.FamilyID, "reuse") // nil → commit
}
if time.Now().After(old.ExpiresAt) {
return ErrInvalidToken
}
next, err := newToken()
if err != nil {
return err
}
if err := tx.MarkRotated(ctx, old.ID); err != nil {
return err
}
child := old.Child(sha256Hex(next), time.Now().Add(30*24*time.Hour))
if err := tx.InsertRefresh(ctx, child); err != nil {
return err
}
access, err := s.jwt.Issue(old.UserID, 15*time.Minute)
pair = TokenPair{Access: access, Refresh: next}
return err
})
if err != nil {
return TokenPair{}, err
}
if reused != nil {
s.events.Publish(ctx, TokenReuseDetected{UserID: reused.UserID, FamilyID: reused.FamilyID})
return TokenPair{}, ErrInvalidToken
}
return pair, nil
}
func newToken() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil { // crypto/rand
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}| Tự làm (bcrypt + JWT)Build it (bcrypt + JWT) | IdP qua OIDC (Keycloak, Auth0, Cognito)IdP over OIDC (Keycloak, Auth0, Cognito) | |
|---|---|---|
| Công sứcEffort | Tự viết đăng ký, quên mật khẩu, xoay token, khoá kýYou write sign-up, password reset, token rotation and key management | Cấu hình realm/client, tích hợp OIDC ở BFFConfigure a realm and client, integrate OIDC in the BFF |
| Tính năngFeatures | MFA, social login, SSO phải tự thêm dầnMFA, social login and SSO are added one by one | MFA, social login, SSO, chính sách mật khẩu có sẵnMFA, social login, SSO and password policy out of the box |
| Kiểm soát, chi phíControl, cost | Toàn quyền giao diện và dữ liệu, không phí theo userFull control of UI and data, no per-user fee | Phụ thuộc nhà cung cấp; Auth0/Cognito tính phí theo MAU, Keycloak phải tự vận hànhVendor dependency; Auth0/Cognito charge per MAU, Keycloak must be operated |
| Chọn khiPick it when | Sản phẩm nhỏ, một ứng dụng, đội có kinh nghiệm bảo mậtA small product, one app, a team with security experience | Nhiều ứng dụng cần SSO, khách doanh nghiệp đòi SAML/MFASeveral apps need SSO, enterprise customers require SAML/MFA |
Hai tab cùng gửi một refresh token sẽ khiến lượt thứ hai thấy ROTATED và thu hồi cả họ, dù không có kẻ trộm. Gộp các lượt refresh đang chờ thành một lượt và phối hợp giữa các tab, đồng thời khoá dòng trong transaction; theo dõi token.reuse_detected tăng sau khi triển khai client mới. Không tự động thử lại refresh khi mất phản hồi và không dùng khoảng ân hạn để cấp thêm token vô điều kiện.Two tabs submitting the same refresh token make the second request see ROTATED and revoke the family, even without theft. Coalesce pending refresh calls and coordinate across tabs, while locking the row in a transaction; watch for token.reuse_detected spikes after client releases. Do not blindly retry refresh after a lost response or use a grace period to issue extra tokens unconditionally.
Spring mặc định rollback khi ném RuntimeException, nên trả 401 có thể vô tình khôi phục token vừa thu hồi. Dùng noRollbackFor cho lỗi nghiệp vụ phù hợp hoặc trả lỗi sau commit như Go; kiểm tra rằng token con cũng trả 401 sau một lần dùng lại. Chỉ xử lý cảnh báo sau commit, và dùng outbox nếu không được phép mất sự kiện khi tiến trình chết.Spring rolls back on RuntimeException by default, so returning 401 can accidentally restore revoked tokens. Use noRollbackFor for the appropriate business exception or return the error after commit as in Go; verify that a child token also returns 401 after reuse. Handle alerts only after commit, and use an outbox if events must survive a process crash.
Thu hồi refresh token chỉ chặn lần gia hạn tiếp theo; JWT còn hạn vẫn qua được Order API nếu API chỉ kiểm cục bộ. Giữ TTL access token ở 15 phút và công bố rõ độ trễ thu hồi; với thao tác nhạy cảm cần chặn ngay, kiểm tra deny list theo jti hoặc session id với TTL bằng phần đời JWT còn lại.Revoking a refresh token only blocks future renewal; an unexpired JWT still passes Order API when validation is local. Keep the access TTL at 15 minutes and state the revocation delay explicitly; for sensitive operations needing immediate blocking, check a jti or session-id deny list with a TTL matching the JWT's remaining lifetime.
Chạy bcrypt trước khi kiểm giới hạn khiến bot đốt CPU: 300 lần kiểm tra mỗi giây ở mức 250 ms cần khoảng 75 lõi CPU nếu mỗi lần chiếm trọn một lõi. Kiểm Redis trước bcrypt, cập nhật bộ đếm và TTL 900 giây nguyên tử, áp ngưỡng 5 lần sai mỗi tài khoản và 20 lần mỗi IP bằng trì hoãn hoặc CAPTCHA. Theo dõi CPU, p95 đăng nhập và số lần chạm ngưỡng để tránh làm khó cả văn phòng dùng chung IP.Running bcrypt before rate limiting lets bots burn CPU: 300 checks per second at 250 ms need roughly 75 CPU cores if each check occupies one core. Check Redis before bcrypt, update counters and their 900-second TTL atomically, and apply thresholds of 5 failures per account and 20 per IP through delays or CAPTCHA. Track CPU, login p95 and threshold hits to avoid penalizing an entire office behind one IP.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
SHA-256 được thiết kế để nhanh; một GPU thử hàng tỷ ứng viên mỗi giây. bcrypt và argon2id chậm có thể điều chỉnh, argon2id còn tốn bộ nhớ nên GPU/ASIC khó song song hoá. Salt chỉ chặn rainbow table, không làm chậm việc dò từng tài khoản.SHA-256 is built to be fast; one GPU tries billions of candidates a second. bcrypt and argon2id are tunably slow, and argon2id is memory-hard, which hurts GPU and ASIC parallelism. A salt only defeats rainbow tables; it does not slow down guessing one account.
Có, tới khi hết exp, vì API chỉ kiểm chữ ký. Đăng xuất thu hồi refresh token nên phiên không gia hạn được. Muốn chặn ngay thì giữ access token ngắn và thêm deny list theo jti hoặc session id trong Redis.Yes, until exp, because APIs only check the signature. Logout revokes the refresh token so the session cannot be extended. To block it immediately keep access tokens short and add a deny list by jti or session id in Redis.
Mỗi token chỉ dùng một lần; dùng xong chuyển ROTATED. Token ROTATED xuất hiện lại nghĩa là có bản sao, nên thu hồi cả family. Nhược điểm: hai tab refresh cùng lúc, hoặc mạng chập chờn làm mất phản hồi, cũng bị coi là dùng lại. Thường cho một khoảng ân hạn vài giây và khoá dòng để xếp hàng.Each token is single-use and becomes ROTATED after use. A ROTATED token showing up again means a copy exists, so the family is revoked. The downside: two tabs refreshing at once, or a lost response on a flaky network, also look like reuse. A grace window of a few seconds plus a row lock to serialise requests is common.
Mọi thứ JavaScript đọc được thì XSS cũng đọc được. BFF là confidential client, giữ client secret và refresh token ở server hoặc trong cookie HttpOnly, nên token không lộ ra trình duyệt. Đây cũng là khuyến nghị trong OAuth 2.0 for Browser-Based Apps của IETF.Anything JavaScript can read, XSS can read. The BFF is a confidential client that keeps the client secret and refresh token on the server or in an HttpOnly cookie, so tokens never reach the browser. It is also what the IETF's OAuth 2.0 for Browser-Based Apps recommends.
Phím 1–4 để chọn đáp án, Enter để kiểm tra.Press 1–4 to choose an answer, Enter to check.
Ôn tập ngắt quãng (spaced repetition): thẻ được lặp lại sau 1 → 3 → 7 → 14 → 30 ngày để củng cố trí nhớ dài hạn.Spaced repetition: cards are repeated after 1 → 3 → 7 → 14 → 30 days to build long-term memory.