工具站 / Agent Skill 广场 / 安全审计与加固
🧩 SKILL.md · 安全审计与加固 · MIT

登录认证体系(OAuth2/JWT/HttpOnly Cookie/CSRF)全链路安全审计

对登录认证全链路(OAuth2 PKCE 流程、JWT 算法与声明校验、HttpOnly/SameSite Cookie 标志、会话固定与 CSRF)进行可执行探测与严格验收审计。

✓ Claude Code✓ Cursor✓ Codex✓ Antigravity
⚡ 选择你的 AI 编程工具 · 一行终端命令直接安装
mkdir -p ~/.claude/skills/oauth2-jwt-session-auth-auditor && curl -fsSL https://ai.yevrix.com/skills/oauth2-jwt-session-auth-auditor/SKILL.md -o ~/.claude/skills/oauth2-jwt-session-auth-auditor/SKILL.md
🛡️ 版权与原创声明:本技能规范由 Yevrix AI 独立原创编写,遵循 MIT 开源协议发布,您可免费用于个人或商业研发团队并自由二次修改。
oauth2-jwt-session-auth-auditor/SKILL.md YAML Frontmatter + Executable SOP
---
name: oauth2-jwt-session-auth-auditor
description: Audit an application's full authentication chain — OAuth2 Authorization Code + PKCE, JWT signature/algorithm/claim verification, HttpOnly/Secure/SameSite cookie flags, session fixation on login, and CSRF defenses. Use when reviewing login flows, token issuance, cookie configuration, or when a security review flags auth weaknesses. Produces concrete probes, Bad-vs-Good fixes, and a verification gate.
---

# OAuth2 PKCE, JWT Algorithm Confusion & Session Fixation Security Auditor

## When to Trigger

- A login, signup, OAuth callback, token refresh, or logout endpoint is added or changed.
- A JWT is decoded/verified anywhere in the codebase (`jwt.decode`, `jwt.verify`, `jsonwebtoken`, `jose`, `PyJWT`, `golang-jwt`).
- Cookies are set for auth (`Set-Cookie` with a session or token).
- A security review, pen-test, or bug bounty report mentions auth, CSRF, or session handling.
- You are onboarding a third-party OAuth provider (Google, GitHub, Auth0, Keycloak, Okta).

## Step 1 — Inventory the Auth Surface

Map every place auth state is created, read, or destroyed. Do not trust the README; grep the code.

```bash
# Find token verification and cookie writes
rg -n --hidden -g '!node_modules' -g '!dist' \
  -e 'jwt\.(decode|verify|sign)' \
  -e 'jsonwebtoken|jose|PyJWT|golang-jwt|jose4j' \
  -e 'Set-Cookie|setCookie|res\.cookie|cookies\.set' \
  -e 'authorization_code|code_verifier|code_challenge|PKCE' \
  -e 'session_regenerate|regenerateSession|req\.session\.regenerate' .

# Find OAuth endpoints and redirect URIs
rg -n -e 'redirect_uri|response_type|scope=|state=' -g '!node_modules' .

# Find CSRF middleware presence
rg -n -e 'csrf|csurf|SameSite|X-CSRF|csrf_token' -g '!node_modules' .
```

Record for each finding: file:line, framework, and whether the value is attacker-controllable.

## Step 2 — Probe OAuth2 PKCE and Redirect Handling

PKCE is mandatory for public clients (SPA, mobile, CLI). Verify the server actually validates `code_verifier` against the stored `code_challenge` and that `state` is bound to the user session.

```bash
# 1. Confirm the authorize endpoint advertises PKCE support
curl -sS 'https://auth.example.com/.well-known/openid-configuration' \
  | jq '{authorization_endpoint, token_endpoint, code_challenge_methods_supported}'

# 2. Confirm the token endpoint rejects a missing/incorrect code_verifier
curl -sS -X POST 'https://auth.example.com/oauth/token' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  --data-urlencode 'grant_type=authorization_code' \
  --data-urlencode 'code=TEST_CODE' \
  --data-urlencode 'redirect_uri=https://app.example.com/callback' \
  --data-urlencode 'client_id=web' \
  --data-urlencode 'code_verifier=WRONG_VERIFIER' \
  -o /dev/null -w '%{http_code}\n'
# Expect 400 invalid_grant. A 200 here is a critical PKCE bypass.

# 3. Confirm state is single-use and bound to the session cookie
curl -sS -i 'https://auth.example.com/oauth/authorize?response_type=code&client_id=web&redirect_uri=https://app.example.com/callback&state=abc&code_challenge=xyz&code_challenge_method=S256' \
  | rg -i 'set-cookie|location'
```

Edge cases to check in code:
- `code_challenge_method` must be `S256`, never `plain` in production.
- `state` must be generated with `crypto.randomUUID()` or `crypto.randomBytes(32)` and stored server-side (or in a signed HttpOnly cookie), then deleted after use.
- `redirect_uri` must be an exact string match against an allowlist — no prefix matching, no wildcard subdomains.

## Step 3 — Audit JWT Verification (Algorithm Confusion)

Algorithm confusion is the #1 JWT bug: the verifier trusts the `alg` header, so an attacker switches `RS256` → `HS256` and signs with the public key, or uses `alg: none`.

```bash
# Decode a token without verifying (safe, for inspection only)
echo "$TOKEN" | cut -d. -f1 | base64 -d 2>/dev/null | jq .
echo "$TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null | jq .

# Forge an alg:none token to test the verifier
python3 - <<'PY'
import base64, json, os
h = base64.urlsafe_b64encode(json.dumps({"alg":"none","typ":"JWT"}).encode()).rstrip(b'=')
p = base64.urlsafe_b64encode(json.dumps({"sub":"admin","role":"admin","exp":9999999999}).encode()).rstrip(b'=')
print((h+b'.'+p+b'.').decode())
PY

# Send it to a protected endpoint; expect 401
curl -sS -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer $FORGED" https://api.example.com/me
```

Required verifier properties:
- Algorithm is pinned in code (`algorithms: ['RS256']`), never read from the token header.
- `exp`, `nbf`, `iat`, `iss`, `aud` are all validated.
- Key material comes from JWKS with `kid` lookup and cache TTL; never from the token.
- Symmetric secrets are ≥ 256 bits and loaded from env/secret manager, not source.

## Step 4 — Cookie Flags, Session Fixation, and CSRF

```bash
# Inspect auth cookie flags on login
curl -sS -i -X POST https://app.example.com/login \
  -H 'Content-Type: application/json' \
  -d '{"email":"a@b.c","password":"x"}' \
  | rg -i '^set-cookie:'
# Require: HttpOnly; Secure; SameSite=Lax|Strict; Path=/; Max-Age bounded

# Session fixation probe: capture pre-login cookie, log in, compare
PRE=$(curl -sS -i https://app.example.com/login | rg -i '^set-cookie: session=' | sed 's/.*session=\([^;]*\).*/\1/')
POST=$(curl -sS -i -X POST https://app.example.com/login -d 'email=a@b.c&password=x' \
  | rg -i '^set-cookie: session=' | sed 's/.*session=\([^;]*\).*/\1/')
[ "$PRE" = "$POST" ] && echo 'VULNERABLE: session not rotated on login' || echo 'OK: rotated'

# CSRF: state-changing request without token should fail
curl -sS -o /dev/null -w '%{http_code}\n' -X POST https://app.example.com/api/email/change \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  --data 'email=attacker@evil.com'
# Expect 403. A 200 means CSRF protection is missing.
```

## High-Risk Anti-Patterns (Bad vs Good)

**JWT algorithm confusion**
```js
// BAD: trusts header alg, allows none
jwt.verify(token, publicKey);

// GOOD: pin algorithm and claims
jwt.verify(token, publicKey, {
  algorithms: ['RS256'],
  issuer: 'https://auth.example.com/',
  audience: 'api.example.com',
  clockTolerance: 5,
});
```

**Cookie flags**
```js
// BAD: JS-readable, sent over HTTP, cross-site
res.cookie('session', sid, { httpOnly: false });

// GOOD
res.cookie('session', sid, {
  httpOnly: true, secure: true, sameSite: 'lax',
  path: '/', maxAge: 1000 * 60 * 60 * 8,
});
```

**Session fixation**
```python
# BAD: keep the same session id after auth
session['user_id'] = user.id

# GOOD: rotate the session id, then bind the user
session.regenerate()
session['user_id'] = user.id
```

**PKCE downgrade**
```python
# BAD: accept plain or missing verifier
token = exchange(code, redirect_uri)

# GOOD: require S256 and verify the stored challenge
assert stored['code_challenge_method'] == 'S256'
assert s256(stored['code_challenge']) == s256(verifier)
```

**CSRF**
```python
# BAD: rely on SameSite alone for state-changing POSTs
@app.post('/api/email/change')
def change_email(): ...

# GOOD: double-submit token + SameSite=Lax
@app.post('/api/email/change')
@csrf_protect
def change_email(): ...
```

## Verification Gate Checklist

- [ ] OAuth2 uses Authorization Code + PKCE with `code_challenge_method=S256`; `plain` rejected.
- [ ] `state` is cryptographically random, single-use, and bound to the user session.
- [ ] `redirect_uri` is exact-match allowlisted; no wildcards or prefix matching.
- [ ] JWT verifier pins `algorithms`, validates `exp`/`nbf`/`iss`/`aud`, and rejects `alg: none`.
- [ ] JWKS keys are fetched by `kid` with cache TTL; no key material from the token.
- [ ] Auth cookies set `HttpOnly`, `Secure`, `SameSite=Lax|Strict`, bounded `Max-Age`, `Path=/`.
- [ ] Session ID is rotated on login and on privilege change; old ID invalidated server-side.
- [ ] State-changing endpoints require a CSRF token (double-submit or synchronizer) in addition to SameSite.
- [ ] Logout invalidates the server-side session and clears the cookie.
- [ ] Forged `alg:none` and `HS256`-with-public-key tokens return 401 in staging.
开发者生态推荐

推荐云主机与 AI 算力基础设施

精选适合部署独立站、自动化脚本与大模型工作流的云底座;通过推广链接注册不增加任何费用,同时支持本站永久免费。
📬 每周精选 · 零垃圾邮件

订阅 Yevrix 独立开发者周刊

每周一封邮件:最新上线免费本地工具、云主机/AI API 实测对比、原创 Agent Skill 与 GitHub 飙升项目精选,随时一键退订。