Web Authentication Implementation Expert
Implement production-ready authentication for web applications.
Stack
- Frontend: TypeScript (React, Next.js, Vue)
- Backend: Python (FastAPI, Flask, Django)
- Standards: OAuth 2.1 (draft), OIDC, WebAuthn, TOTP RFC 6238, OWASP ASVS 5.0
Orchestrator
This skill dispatches to specialized sub-agents based on the task:
| Sub-Agent |
Purpose |
Dispatch When |
oauth-implementer |
OAuth 2.1, OIDC, PKCE, social login |
User needs OAuth/social login |
passkey-implementer |
WebAuthn, FIDO2, passkeys |
User needs passkeys/passwordless |
mfa-implementer |
TOTP, hardware keys, step-up auth |
User needs MFA |
security-hardener |
CSRF, XSS, headers, rate limiting |
User needs security hardening |
compliance-checker |
CCSS, SOC 2, GDPR, ASVS verification |
User mentions compliance |
Context Efficiency: Load only the relevant sub-agent's references to minimize context usage.
Quick Method Selection
| App Type |
Primary Auth |
MFA |
Session |
| Consumer SaaS |
Social login (Google/Apple) |
Optional TOTP |
JWT in HttpOnly cookie |
| Enterprise B2B |
OIDC SSO |
Required (TOTP/hardware key) |
Server-side sessions |
| Crypto/Financial |
Passkeys + password fallback |
Required + step-up auth |
Short-lived JWT + refresh |
| Internal tools |
Corporate SSO |
Policy-based |
Server-side sessions |
Implementation Workflow
- Determine requirements → Read
references/decision-framework.md
- Implement primary auth method → Read appropriate
references/methods/ file
- Add social providers if needed → Read
references/social-providers/
- Implement session management → Read
references/session-management/
- Add MFA if required → Read
references/mfa/
- Apply security hardening → Read
references/security/
- Verify compliance → Read
references/compliance/ if applicable
Core Patterns (Quick Reference)
OAuth 2.1 Authorization Code + PKCE
Frontend (TypeScript):
// Generate PKCE pair
function generatePKCE(): { verifier: string; challenge: string } {
const verifier = crypto.randomUUID() + crypto.randomUUID();
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const hash = await crypto.subtle.digest('SHA-256', data);
const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
return { verifier, challenge };
}
// Store verifier in sessionStorage, send challenge to /authorize
sessionStorage.setItem('pkce_verifier', pkce.verifier);
Backend (Python/FastAPI):
from authlib.integrations.starlette_client import OAuth
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
oauth = OAuth()
oauth.register(
name="google",
client_id=settings.GOOGLE_CLIENT_ID,
client_secret=settings.GOOGLE_CLIENT_SECRET,
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": "openid email profile"},
)
@app.get("/auth/google")
async def google_login(request: Request):
redirect_uri = request.url_for("google_callback")
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.get("/auth/google/callback")
async def google_callback(request: Request):
token = await oauth.google.authorize_access_token(request)
user_info = token.get("userinfo")
# Create session, return JWT
Password Hashing (Argon2id)
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher(
time_cost=2, # iterations
memory_cost=19456, # 19 MiB
parallelism=1,
hash_len=32,
salt_len=16
)
def hash_password(password: str) -> str:
return ph.hash(password)
def verify_password(hash: str, password: str) -> bool:
try:
ph.verify(hash, password)
return True
except VerifyMismatchError:
return False
JWT Session Cookie
from datetime import datetime, timedelta
import jwt
def create_session_token(user_id: str, secret: str) -> str:
payload = {
"sub": user_id,
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(hours=1),
}
return jwt.encode(payload, secret, algorithm="HS256")
def set_session_cookie(response, token: str):
response.set_cookie(
key="session",
value=token,
httponly=True,
secure=True,
samesite="lax",
max_age=3600,
)
TOTP MFA
import pyotp
def generate_totp_secret() -> str:
return pyotp.random_base32()
def get_totp_uri(secret: str, email: str, issuer: str) -> str:
return pyotp.totp.TOTP(secret).provisioning_uri(
name=email, issuer_name=issuer
)
def verify_totp(secret: str, code: str) -> bool:
totp = pyotp.TOTP(secret)
return totp.verify(code, valid_window=1) # Allow 30s drift
References
Methods
references/methods/oauth-oidc-pkce.md - OAuth 2.1, OIDC, PKCE implementation
references/methods/passkeys-webauthn.md - FIDO2/WebAuthn/Passkeys
references/methods/magic-links.md - Email passwordless
references/methods/password-auth.md - Traditional auth + hashing
Social Providers
references/social-providers/overview.md - Common patterns, account linking
references/social-providers/google.md - Google Sign-In
references/social-providers/apple.md - Sign in with Apple
references/social-providers/facebook.md - Facebook Login
references/social-providers/github.md - GitHub OAuth
MFA
references/mfa/overview.md - Method comparison
references/mfa/totp.md - TOTP implementation
references/mfa/hardware-keys.md - YubiKey, FIDO2 keys
references/mfa/step-up-auth.md - Re-auth for sensitive operations
Session Management
references/session-management/jwt-vs-cookies.md - When to use which
references/session-management/token-storage.md - Secure storage (TypeScript)
references/session-management/session-security.md - Timeouts, rotation
Security
references/security/password-hashing.md - Argon2id, bcrypt, migration
references/security/csrf-xss-protection.md - Attack prevention
references/security/rate-limiting.md - Brute force protection
Compliance
references/compliance/ccss.md - Crypto app requirements
references/compliance/soc2.md - SOC 2 auth requirements
references/compliance/gdpr-data.md - GDPR considerations
Sub-Agents
sub_agents/oauth-implementer.md - OAuth 2.1, OIDC, PKCE flows
sub_agents/passkey-implementer.md - WebAuthn/FIDO2/Passkeys
sub_agents/mfa-implementer.md - TOTP, hardware keys, step-up auth
sub_agents/security-hardener.md - CSRF, XSS, headers, rate limiting
sub_agents/compliance-checker.md - CCSS, SOC 2, GDPR verification
Workflows
workflows/new-crypto-app.md - Crypto dashboard auth setup
workflows/new-standard-app.md - Standard web app auth
workflows/add-social-login.md - Adding OAuth providers
workflows/add-mfa.md - Implementing MFA
workflows/security-audit.md - Auth security review
Orchestrator Agent
This skill has an associated orchestrator agent at .claude/agents/web-auth-expert.md that coordinates the sub-agents and workflows. The orchestrator:
- Identifies the authentication domain (OAuth, passkeys, MFA, security, compliance)
- Dispatches to appropriate sub-agents
- Coordinates multi-agent tasks for complex requests
- Provides code for both TypeScript frontend and Python backend
Research
references/RESEARCH.md - Latest auth best practices (January 2025)
1---2name: web-auth-expert3description: Implement authentication for web applications with TypeScript frontends and Python backends. Use for: OAuth 2.1/OIDC with PKCE, social login (Google, Apple, Facebook, GitHub), passkeys/WebAuthn/FIDO2, MFA (TOTP, hardware keys, push notifications), magic links, password authentication with Argon2id, session management (JWT/cookies), CSRF/XSS protection. Includes crypto application requirements (CCSS, step-up auth, withdrawal protection). All implementations follow OWASP ASVS 5.0 and current security best practices.4---56# Web Authentication Implementation Expert78Implement production-ready authentication for web applications.910## Stack11- **Frontend**: TypeScript (React, Next.js, Vue)12- **Backend**: Python (FastAPI, Flask, Django)13- **Standards**: OAuth 2.1 (draft), OIDC, WebAuthn, TOTP RFC 6238, OWASP ASVS 5.01415## Orchestrator1617This skill dispatches to specialized sub-agents based on the task:1819| Sub-Agent | Purpose | Dispatch When |20|-----------|---------|---------------|21| `oauth-implementer` | OAuth 2.1, OIDC, PKCE, social login | User needs OAuth/social login |22| `passkey-implementer` | WebAuthn, FIDO2, passkeys | User needs passkeys/passwordless |23| `mfa-implementer` | TOTP, hardware keys, step-up auth | User needs MFA |24| `security-hardener` | CSRF, XSS, headers, rate limiting | User needs security hardening |25| `compliance-checker` | CCSS, SOC 2, GDPR, ASVS verification | User mentions compliance |2627**Context Efficiency**: Load only the relevant sub-agent's references to minimize context usage.2829## Quick Method Selection3031| App Type | Primary Auth | MFA | Session |32|----------|--------------|-----|---------|33| Consumer SaaS | Social login (Google/Apple) | Optional TOTP | JWT in HttpOnly cookie |34| Enterprise B2B | OIDC SSO | Required (TOTP/hardware key) | Server-side sessions |35| Crypto/Financial | Passkeys + password fallback | Required + step-up auth | Short-lived JWT + refresh |36| Internal tools | Corporate SSO | Policy-based | Server-side sessions |3738## Implementation Workflow39401. **Determine requirements** → Read `references/decision-framework.md`412. **Implement primary auth method** → Read appropriate `references/methods/` file423. **Add social providers if needed** → Read `references/social-providers/`434. **Implement session management** → Read `references/session-management/`445. **Add MFA if required** → Read `references/mfa/`456. **Apply security hardening** → Read `references/security/`467. **Verify compliance** → Read `references/compliance/` if applicable4748## Core Patterns (Quick Reference)4950### OAuth 2.1 Authorization Code + PKCE5152**Frontend (TypeScript):**53```typescript54// Generate PKCE pair55function generatePKCE(): { verifier: string; challenge: string } {56 const verifier = crypto.randomUUID() + crypto.randomUUID();57 const encoder = new TextEncoder();58 const data = encoder.encode(verifier);59 const hash = await crypto.subtle.digest('SHA-256', data);60 const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))61 .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');62 return { verifier, challenge };63}6465// Store verifier in sessionStorage, send challenge to /authorize66sessionStorage.setItem('pkce_verifier', pkce.verifier);67```6869**Backend (Python/FastAPI):**70```python71from authlib.integrations.starlette_client import OAuth72from fastapi import FastAPI, Request73from fastapi.responses import RedirectResponse7475oauth = OAuth()76oauth.register(77 name="google",78 client_id=settings.GOOGLE_CLIENT_ID,79 client_secret=settings.GOOGLE_CLIENT_SECRET,80 server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",81 client_kwargs={"scope": "openid email profile"},82)8384@app.get("/auth/google")85async def google_login(request: Request):86 redirect_uri = request.url_for("google_callback")87 return await oauth.google.authorize_redirect(request, redirect_uri)8889@app.get("/auth/google/callback")90async def google_callback(request: Request):91 token = await oauth.google.authorize_access_token(request)92 user_info = token.get("userinfo")93 # Create session, return JWT94```9596### Password Hashing (Argon2id)9798```python99from argon2 import PasswordHasher100from argon2.exceptions import VerifyMismatchError101102ph = PasswordHasher(103 time_cost=2, # iterations104 memory_cost=19456, # 19 MiB105 parallelism=1,106 hash_len=32,107 salt_len=16108)109110def hash_password(password: str) -> str:111 return ph.hash(password)112113def verify_password(hash: str, password: str) -> bool:114 try:115 ph.verify(hash, password)116 return True117 except VerifyMismatchError:118 return False119```120121### JWT Session Cookie122123```python124from datetime import datetime, timedelta125import jwt126127def create_session_token(user_id: str, secret: str) -> str:128 payload = {129 "sub": user_id,130 "iat": datetime.utcnow(),131 "exp": datetime.utcnow() + timedelta(hours=1),132 }133 return jwt.encode(payload, secret, algorithm="HS256")134135def set_session_cookie(response, token: str):136 response.set_cookie(137 key="session",138 value=token,139 httponly=True,140 secure=True,141 samesite="lax",142 max_age=3600,143 )144```145146### TOTP MFA147148```python149import pyotp150151def generate_totp_secret() -> str:152 return pyotp.random_base32()153154def get_totp_uri(secret: str, email: str, issuer: str) -> str:155 return pyotp.totp.TOTP(secret).provisioning_uri(156 name=email, issuer_name=issuer157 )158159def verify_totp(secret: str, code: str) -> bool:160 totp = pyotp.TOTP(secret)161 return totp.verify(code, valid_window=1) # Allow 30s drift162```163164## References165166### Methods167- `references/methods/oauth-oidc-pkce.md` - OAuth 2.1, OIDC, PKCE implementation168- `references/methods/passkeys-webauthn.md` - FIDO2/WebAuthn/Passkeys169- `references/methods/magic-links.md` - Email passwordless170- `references/methods/password-auth.md` - Traditional auth + hashing171172### Social Providers173- `references/social-providers/overview.md` - Common patterns, account linking174- `references/social-providers/google.md` - Google Sign-In175- `references/social-providers/apple.md` - Sign in with Apple176- `references/social-providers/facebook.md` - Facebook Login177- `references/social-providers/github.md` - GitHub OAuth178179### MFA180- `references/mfa/overview.md` - Method comparison181- `references/mfa/totp.md` - TOTP implementation182- `references/mfa/hardware-keys.md` - YubiKey, FIDO2 keys183- `references/mfa/step-up-auth.md` - Re-auth for sensitive operations184185### Session Management186- `references/session-management/jwt-vs-cookies.md` - When to use which187- `references/session-management/token-storage.md` - Secure storage (TypeScript)188- `references/session-management/session-security.md` - Timeouts, rotation189190### Security191- `references/security/password-hashing.md` - Argon2id, bcrypt, migration192- `references/security/csrf-xss-protection.md` - Attack prevention193- `references/security/rate-limiting.md` - Brute force protection194195### Compliance196- `references/compliance/ccss.md` - Crypto app requirements197- `references/compliance/soc2.md` - SOC 2 auth requirements198- `references/compliance/gdpr-data.md` - GDPR considerations199200## Sub-Agents201- `sub_agents/oauth-implementer.md` - OAuth 2.1, OIDC, PKCE flows202- `sub_agents/passkey-implementer.md` - WebAuthn/FIDO2/Passkeys203- `sub_agents/mfa-implementer.md` - TOTP, hardware keys, step-up auth204- `sub_agents/security-hardener.md` - CSRF, XSS, headers, rate limiting205- `sub_agents/compliance-checker.md` - CCSS, SOC 2, GDPR verification206207## Workflows208- `workflows/new-crypto-app.md` - Crypto dashboard auth setup209- `workflows/new-standard-app.md` - Standard web app auth210- `workflows/add-social-login.md` - Adding OAuth providers211- `workflows/add-mfa.md` - Implementing MFA212- `workflows/security-audit.md` - Auth security review213214## Orchestrator Agent215216This skill has an associated orchestrator agent at `.claude/agents/web-auth-expert.md` that coordinates the sub-agents and workflows. The orchestrator:217218- Identifies the authentication domain (OAuth, passkeys, MFA, security, compliance)219- Dispatches to appropriate sub-agents220- Coordinates multi-agent tasks for complex requests221- Provides code for both TypeScript frontend and Python backend222223## Research224- `references/RESEARCH.md` - Latest auth best practices (January 2025)