OAuth 2.0 là authorization framework — delegated authorization (không phải authentication).
Phân biệt: OAuth cho authorization (app có quyền gì), OpenID Connect (OIDC) là layer trên OAuth cho authentication (ai đang login, trả về ID token).
Authorization Code flow chi tiết:
- App redirect user đến Authorization Server với client_id, redirect_uri, scope, state (CSRF protection), code_challenge (PKCE);
- User authenticate và consent;
- Auth Server redirect về app với authorization code;
- App exchange code cho access token qua back-channel request (POST, client_secret không expose trong URL);
- App dùng access token để call protected APIs;
- Refresh token để get new access token khi expire
PKCE (Proof Key for Code Exchange): app tạo code_verifier (random string), gửi code_challenge = hash(code_verifier) trong step 1, gửi code_verifier trong step 4 — server verify hash match — ngăn authorization code interception attack, bắt buộc cho public clients (SPA, mobile).
Implicit flow: deprecated — trả access token trực tiếp trong URL, exposure risk.
Client credentials flow: machine-to-machine, không có user — backend service gọi API.
Scopes: granular permissions (read:email, write:calendar) — request chỉ scopes cần thiết.
Token storage: access token trong memory (SPA), refresh token trong HttpOnly cookie — không dùng localStorage cho sensitive tokens.
OAuth 2.1 (đang chuẩn hóa) gộp các best practices: PKCE bắt buộc cho mọi client, xóa Implicit và Resource Owner Password Credentials flows.