跳到內容

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: 顯示結果

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_idClient 的唯一識別碼
redirect_uri授權完成後導向的 callback URL
scope申請的授權範圍
state防止 CSRF 攻擊的隨機值,callback 時需驗證

使用者在 Authorization Server 的頁面登入並確認授權範圍。

Authorization Server 將使用者導回 redirect_uri,附帶一次性的授權碼:

https://app.example.com/callback?code=AUTH_CODE&state=RANDOM_STATE_VALUE

⚠️ 重要:收到 callback 後必須驗證 state 值是否與 Step 1 一致,以防止 CSRF 攻擊。

Client 的後端向 Authorization Server 的 Token 端點發送請求:

POST /token HTTP/1.1
Host: auth.example.com
Content-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_SECRET

Authorization Server 回傳:

{
"access_token": "eyJhbGciOiJSUzI1NiJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "8xLOxBtZp8",
"scope": "read:profile"
}

後端用 Authorization: Bearer header 呼叫 Resource Server:

GET /api/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9...

Authorization Code Flow 的關鍵安全設計:

  1. Authorization Code 是一次性的:只能使用一次,且有效期極短(通常 1 分鐘)
  2. Token 交換在後端進行client_secret 只在後端使用,不會暴露給瀏覽器
  3. Access Token 不經過瀏覽器:Token 直接在後端保管,不在 URL 或瀏覽器歷史紀錄中出現
  4. state 防 CSRF:防止攻擊者偽造 callback 請求

OAuth 2.1 建議所有使用 Authorization Code Flow 的 Client 都應該使用 PKCE,包含有後端的 Confidential Client。PKCE 可以防止授權碼攔截攻擊(Authorization Code Interception Attack)。

→ 詳見 Authorization Code + PKCE