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 與 OIDC:授權與認證的標準
OAuth 2.0 的四種授權流程
| 流程 | 使用場景 | 安全性 | |:----|:--------|:------| | Authorization Code | 後端應用(最常見) | 最高 | | PKCE | 單頁應用(SPA)、行動 App | 高 | | Client Credentials | 機器對機器(M2M) | 中 | | Implicit | 已被淘汰,不要用 | 低 |
OAuth vs OIDC
OAuth 2.0 解決的是「授權」(Authorization)——允許第三方存取特定資源。OIDC(OpenID Connect)在 OAuth 之上加入「認證」(Authentication)——確認使用者身份。
簡單說:OAuth 讓 App 可以存取你的 Google 行事曆,OIDC 讓 App 知道你是誰。
下一章預告:SSO 與 SAML
OAuth/OIDC 是授權和認證的標準。下一章的 SSO 和 SAML 是企業級的單一登入解決方案。