OAuth 2.0 與 OIDC
Vibe Prompt
「幫我實作 OAuth 2.0 Authorization Code Flow:前端跳轉到 Google 登入,後端接收 callback 換取 Token。」
四種 Flow
| Flow | 使用場景 | |------|---------| | Authorization Code | 後端有 Server 的應用 | | Implicit | SPA(已不推薦) | | Resource Owner Password | 高度信任的應用(不推薦) | | Client Credentials | 機器對機器 |
Authorization Code Flow
1. 前端 → Google: 跳轉到授權頁面
2. Google → 前端: 授權碼 code
3. 前端 → 後端: 傳授權碼
4. 後端 → Google: 用 code + client_secret 換 token
5. Google → 後端: access_token + id_token + refresh_token
6. 後端 → 前端: session cookie
驗證 ID Token
import jwt
# Google 的 JWKS 端點
jwks_url = "https://www.googleapis.com/oauth2/v3/certs"
# 驗證 id_token
id_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
claims = jwt.decode(
id_token,
jwks_client.get_signing_key_from_jwt(id_token).key,
algorithms=["RS256"],
audience=CLIENT_ID,
issuer="https://accounts.google.com"
)
print(f"使用者: {claims['sub']}")
print(f"Email: {claims.get('email')}")
print(f"名字: {claims.get('given_name')}")
簡化授權
使用 Supabase Auth 即可完成 OAuth,不需自行實作。