Authorization Code Flow
Authorization Code Flow 是 OAuth 2.0 最核心、最安全的授權流程,由 RFC 6749 Section 4.1 定義。它適合有後端伺服器的 Web 應用程式,核心設計是讓 Access Token 從不暴露在使用者的瀏覽器中。
- 有後端伺服器的 Web 應用(Node.js、Ruby on Rails、Laravel 等)
- 可以安全儲存 Client Secret 的應用(稱為 Confidential Client)
若是行動 App 或純前端 SPA,請改用 Authorization Code + PKCE。
sequenceDiagram
actor User as 使用者 Browser
participant Client as Client (後端)
participant AuthServer as Authorization Server
participant Resource as Resource Server
User->>Client: 點擊「登入」
Client-->>User: 302 Redirect
User->>AuthServer: 使用者登入並授權
AuthServer-->>User: Redirect to callback?code=AUTH_CODE
User->>Client: GET /callback?code=AUTH_CODE
Client->>AuthServer: POST /token (code + client_secret)
AuthServer->>Client: Access Token
Client->>Resource: GET /api/resource + Bearer Token
Resource->>Client: 資源資料
Client->>User: 顯示結果
Step 1:組合授權請求 URL
Section titled “Step 1:組合授權請求 URL”Client 將使用者導向 Authorization Server 的授權端點:
https://auth.example.com/authorize? response_type=code &client_id=YOUR_CLIENT_ID &redirect_uri=https://app.example.com/callback &scope=read:profile &state=RANDOM_STATE_VALUE| 參數 | 說明 |
|---|---|
response_type=code | 告知 Authorization Server 回傳授權碼 |
client_id | Client 的唯一識別碼 |
redirect_uri | 授權完成後導向的 callback URL |
scope | 申請的授權範圍 |
state | 防止 CSRF 攻擊的隨機值,callback 時需驗證 |
Step 2:使用者授權
Section titled “Step 2:使用者授權”使用者在 Authorization Server 的頁面登入並確認授權範圍。
Step 3:收到 Authorization Code
Section titled “Step 3:收到 Authorization Code”Authorization Server 將使用者導回 redirect_uri,附帶一次性的授權碼:
https://app.example.com/callback?code=AUTH_CODE&state=RANDOM_STATE_VALUE⚠️ 重要:收到 callback 後必須驗證
state值是否與 Step 1 一致,以防止 CSRF 攻擊。
Step 4:用 Code 換 Token
Section titled “Step 4:用 Code 換 Token”Client 的後端向 Authorization Server 的 Token 端點發送請求:
POST /token HTTP/1.1Host: auth.example.comContent-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=AUTH_CODE&redirect_uri=https://app.example.com/callback&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRETAuthorization Server 回傳:
{ "access_token": "eyJhbGciOiJSUzI1NiJ9...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "8xLOxBtZp8", "scope": "read:profile"}Step 5:使用 Access Token
Section titled “Step 5:使用 Access Token”後端用 Authorization: Bearer header 呼叫 Resource Server:
GET /api/profile HTTP/1.1Host: api.example.comAuthorization: Bearer eyJhbGciOiJSUzI1NiJ9...為什麼安全?
Section titled “為什麼安全?”Authorization Code Flow 的關鍵安全設計:
- Authorization Code 是一次性的:只能使用一次,且有效期極短(通常 1 分鐘)
- Token 交換在後端進行:
client_secret只在後端使用,不會暴露給瀏覽器 - Access Token 不經過瀏覽器:Token 直接在後端保管,不在 URL 或瀏覽器歷史紀錄中出現
state防 CSRF:防止攻擊者偽造 callback 請求
與 PKCE 的關係
Section titled “與 PKCE 的關係”OAuth 2.1 建議所有使用 Authorization Code Flow 的 Client 都應該使用 PKCE,包含有後端的 Confidential Client。PKCE 可以防止授權碼攔截攻擊(Authorization Code Interception Attack)。