OAuth 2.0 & OpenID Connect
🔥 Vibe Prompt
"Implement OAuth 2.0 Authorization Code flow with PKCE and OIDC."
OAuth 2.0 Flows
Authorization Code (with PKCE): [Recommended for web/mobile]
User → App → Auth Server → Login Page → Auth Code → Token
Client Credentials: [Machine-to-machine]
App → Auth Server → Access Token (no user involved)
Implicit (deprecated): [Don't use - security issues]
Authorization Code + PKCE
import requests, hashlib, base64, secrets
# 1. Generate PKCE
code_verifier = secrets.token_urlsafe(64)
code_challenge = base64.urlsafe_b64encode(
hashlib.sha256(code_verifier.encode()).digest()
).rstrip("=").decode()
# 2. Redirect user to auth URL
auth_url = f"https://auth.example.com/authorize?" \
f"response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT}" \
f"&code_challenge={code_challenge}&code_challenge_method=S256"
# 3. Exchange code for token
token_resp = requests.post("https://auth.example.com/token", data={
"grant_type": "authorization_code",
"code": authorization_code,
"redirect_uri": REDIRECT,
"client_id": CLIENT_ID,
"code_verifier": code_verifier
})
access_token = token_resp.json()["access_token"]
# 4. Call API
api_resp = requests.get("https://api.example.com/user", headers={
"Authorization": f"Bearer {access_token}"
})
OpenID Connect (OIDC)
# OIDC extends OAuth 2.0 with identity layer
# Returns id_token (JWT) containing user info
def decode_jwt(token):
import jwt
# Verify signature using JWKS from auth server
jwks_url = "https://auth.example.com/.well-known/jwks.json"
jwks_client = jwt.PyJWKClient(jwks_url)
signing_key = jwks_client.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience=CLIENT_ID,
issuer="https://auth.example.com/"
)
return claims # Contains sub, name, email, etc.
# id_token payload example:
# {
# "sub": "user_123",
# "name": "Alice",
# "email": "alice@example.com",
# "iss": "https://auth.example.com/",
# "aud": "myapp",
# "exp": 1700000000
# }
Scopes & Roles
# Scopes: fine-grained permissions
scope: "openid profile email orders:read orders:write"
# Typical scopes:
- openid: required for OIDC
- profile: name, picture
- email: email address
- orders:read: view orders
- orders:write: create orders
Token Types
| Token | Purpose | Format | Expiry | |-------|---------|--------|--------| | Access Token | Call API | JWT or opaque | 1 hour | | Refresh Token | Get new access token | Opaque | 30 days | | ID Token | User identity (OIDC) | JWT | 1 hour |
Best Practices
- Always use PKCE (even for server-side apps)
- Never use Implicit flow
- Store tokens securely (httpOnly cookie, secure)
- Validate id_token signature and claims
- Use short-lived access tokens (15-60 min)
- Implement token rotation for refresh tokens
為什麼要學OAuth 2.0 與 OpenID Connect?
OAuth 2.0 與 OpenID Connect 是 security-iam 課程的核心章節之一。
在真實世界中
OAuth 2.0 與 OpenID Connect 並不是課本上的理論——它在真實的軟體開發中頻繁出現。無論你是正在接案、準備面試,還是想要提升自己的技術深度,理解這個主題都能讓你直接受益。
你將從本章獲得
- 🎯 完整的知識體系:從核心原理到實作細節,條理分明
- 💻 可運行的程式碼:每段程式碼都是完整的,可直接執行
- 🔍 除錯技巧:常見錯誤的分析與解決方案
- 🚀 下一步指引:學完後該往哪個方向繼續深入
銜接下一章
本章為你建立了 OAuth 2.0 與 OpenID Connect 的完整知識基礎。下一章將在此基礎上,帶你探索更進階的真實世界應用場景——你將學會如何將本章所學應用到更複雜的問題中。