API 安全 (API Security)

核心區分:Authentication vs Authorization

概念 問題 目的
Authentication (AuthN) 你是誰? 確認使用者 / 服務身份是否合法
Authorization (AuthZ) 你能做什麼? 判斷已驗證身份是否有權限執行某操作 / 存取資源
簡單記法

AuthN = Who you are
AuthZ = What you can do

先 AuthN 後 AuthZ —— 不知道你是誰,就無法判斷你能做什麼。


Authentication 方式

1. API Key

GET /users/123
X-API-Key: abc123xyz

2. Basic Auth

Authorization: Basic dXNlcjpwYXNz   # base64(user:pass)

3. Token-based(Session Token / JWT)

Authorization: Bearer eyJhbGciOiJIUzI1NiI...

流程

Client ──login(id/pw)──► Server
                           │
                           ▼ 驗證 + 簽章
Client ◄──access token──── Server
   │
   │ 之後每次 request 帶上 token
   ▼
Server 驗章 → 取得 user 資訊 → 處理
概念 生命週期 用途
Access Token 短期(幾分鐘到幾小時) 每次 API 呼叫驗證
Refresh Token 長期 Access Token 過期時換取新的 access

JWT(JSON Web Token) 三段式:header.payload.signature

JWT 陷阱

  • JWT payload 只做 base64 編碼,不是加密 → 不要放敏感資料
  • 無法主動撤銷(除非配黑名單)→ Access token 要短
  • alg: none 漏洞 → 一定要驗證 algorithm

4. OAuth 2.0

第三方授權框架(不是 authentication,是 delegated authorization):

User ── 同意授權 ──► Authorization Server
                         │
                         ▼ 發 access token
Third-party App ◄─────── Auth Server
      │
      │ 帶 token 呼叫
      ▼
Resource Server (例如 Google Drive API)

場景:Google / Facebook / GitHub 登入;第三方應用存取用戶資料

OAuth 2.0 ≠ OpenID Connect

  • OAuth 2.0:授權(access X's Google Drive)
  • OIDC:基於 OAuth 的 身份驗證(確認「就是 X 本人」)

5. mTLS(Mutual TLS)

雙方都要出示憑證:

Client ──cert──► Server
       ◄──cert── Server
       (雙方互驗後才建立連線)

Authorization 模型

1. RBAC(Role-Based Access Control)

根據「角色」控制權限。

User → Role → Permissions
角色 允許操作
Admin GET /usersDELETE /users/{id}
Editor POST /articlesPUT /articles/{id}
Viewer GET /articles/{id}

2. ABAC(Attribute-Based Access Control)

根據「屬性」決定,屬性可以是時間、地點、部門、資源標籤等。

if user.department == "HR" and resource.type == "payroll":
    allow
屬性類型 範例
使用者屬性 department = HR → 可存取 /payroll
環境屬性 只有辦公室 IP 網段能呼叫 /internal-api
資源屬性 文件標為 Confidential → 只有 clearance ≥ 3 的人可讀

3. Scope-based(OAuth Scopes)

權限隨 Token 的 scope 一起發放。

Authorization: Bearer <token>
# token scope = "repo read:user"

GitHub API 範例:

Scope 可做的事
repo 存取私人 repo
read:user 只能讀取使用者基本資訊
write:org 可修改組織資訊

三種模型對比

模型 粒度 複雜度 適合場景
RBAC 角色層級 內部管理系統、職能清晰
ABAC 屬性層級 金融、政府、需要 policy 引擎
Scope Token 維度 第三方授權、API 開放平台

實務常 混用:RBAC 定主架構 + ABAC 補細節 + Scope 處理外部授權。


API 設計實例

Authentication 檢查

GET /users/123
Authorization: Bearer <JWT_TOKEN>

Server:驗證 JWT 簽章 → token 有效 → 取得 user_id。

Authorization 檢查

if token.user_id == 123:
    allow  # 查自己
elif "admin" in token.roles:
    allow  # admin 可查任何人
else:
    return 403 Forbidden
401 vs 403 對應

  • 401 Unauthorized → Authentication 失敗(沒 token / token 無效)
  • 403 Forbidden → Authorization 失敗(有身份但沒權限)


常見配對

場景 AuthN AuthZ
公司內部 Web app JWT RBAC
第三方 App 存取用戶 OAuth 2.0 Scope
內部微服務 mTLS Service identity
金融 / 政府系統 JWT + mTLS ABAC
簡單內部 API API Key Allowlist

Simplification-with-exceptions

邊界情況

  • OAuth 2.0 不做 authentication → 要 authn 用 OIDC
  • JWT 不是魔法 → revocation 難處理;token 要短 + refresh
  • API Key 不是完全廢棄 → 內部 / 低敏感 API 仍常用
  • mTLS 並非外部禁用 → B2B 合作夥伴也常用
  • Rate limiting 也是 security → 防 DoS、防暴力破解,但不在此圖中


額外安全考量(本章未深入,但常一起出現)