Trung BìnhBảo Mật iconBảo Mật

OAuth 2.0 là gì? Luồng Authorization Code flow hoạt động thế nào?

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:

  1. App redirect user đến Authorization Server với client_id, redirect_uri, scope, state (CSRF protection), code_challenge (PKCE);
  2. User authenticate và consent;
  3. Auth Server redirect về app với authorization code;
  4. App exchange code cho access token qua back-channel request (POST, client_secret không expose trong URL);
  5. App dùng access token để call protected APIs;
  6. 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.

Xem toàn bộ Bảo Mật cùng filter theo level & chủ đề con.

Mở danh sách Bảo Mật