backend-auth-patterns
Use when the user asks about authentication, JWT login with refresh tokens, sessions, OAuth 2.0 / OIDC login, password hashing, MFA, passwordless or refresh…
от j4flmao★ 47 звёзд на GitHub
Установить backend-auth-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Backend Auth Patterns
Purpose
Implement authentication and authorization that is secure by default. Every endpoint must have an auth check. No secrets in code. No plaintext passwords.
Agent Protocol
Trigger
Exact user phrases: "auth", "authentication", "authorization", "JWT", "OAuth", "RBAC", "permissions", "login", "session", "refresh token", "guard", "middleware auth", "access control", "secure endpoint".
Input Context
- Application type (SPA, mobile, M2M, server-rendered).
- Security requirements level (basic auth, enterprise SSO, API-key M2M).
- Existing auth infrastructure (if any).
Output Artifact
Auth design as text. No file output.
Response Format
Auth strategy: {strategy name}
Rationale: {one sentence}
Token structure: {claims}
Auth middleware: {location and logic}
Authorization model: {model name and role/permission list}
Completion Criteria
- Auth strategy selected based on application type
- Token structure defined with minimum viable claims
- Refresh token rotation specified
- Authorization model defined (RBAC or ABAC)
- Auth middleware placement specified (Infrastructure layer)
- Password hashing algorithm specified (bcrypt/argon2)
- Brute force protection specified
- No secrets hardcoded in any code example
Architecture Decision Trees
Auth Strategy Selection
Browser-based SPA?
├── Yes → JWT with refresh tokens in httpOnly cookies (prevents XSS token theft)
│ └── CSRF protection required (SameSite=Strict + CSRF token)
└── No → Mobile app?
├── Yes → JWT with refresh tokens in secure device storage (Keychain/Keystore)
│ └── No CSRF needed (native apps can set custom headers)
└── No → Server-side rendered app?
├── Yes → Session-based auth with Redis store (simpler, CSRF protection built-in)
└── No → M2M service?
├── Yes → API Key (simple) or OAuth2 Client Credentials (standard)
└── No → Third-party login?
└── OAuth2 / OIDC delegated to provider
Token Signing Algorithm
Single service / monolith?
├── Yes → HMAC with HS256 (simpler, faster, one secret to manage)
└── No → Multiple services?
├── Yes → RSA with RS256 or EC with ES256 (public key distribution, no shared secret)
└── Cloud-native with JWKS endpoint?
└── RS256 with JWKS rotation (standard for OIDC)
Session vs JWT Decision Tree
Do you need to revoke sessions immediately?
├── Yes → Session-based (server-side state, immediate revocation)
└── No → Is horizontal scaling a priority?
├── Yes → JWT (stateless, no shared session store)
└── No → Session-based (simpler, built-in revocation)
Is CSRF protection a concern?
├── Yes → Session with SameSite=Strict cookie + CSRF token
└── No → JWT with Bearer header (CSRF inherently protected)
Workflow
Step 1: Choose Auth Strategy
| Application Type | Strategy | Token Type | Storage |
|---|---|---|---|
| SPA (browser) | JWT + Refresh Token | Access in memory, Refresh in httpOnly cookie | Memory + Cookie |
| Mobile app | JWT + Refresh Token | Both in secure storage | Keychain/Keystore |
| M2M service | API Key or Client Credentials | Static key or short-lived JWT | Env/Secrets |
| Server-rendered app | Session + Cookie | Session ID in signed cookie | Redis store |
| Third-party login | OAuth2 / OIDC | Delegated to provider | Provider-managed |
| Enterprise SSO | OIDC with SAML | Delegated to IdP | IdP-managed |
Step 2: JWT Implementation
Token claims (minimum):
{
"sub": "user-uuid",
"role": "admin",
"iat": 1700000000,
"exp": 1700086400
}
Common extended claims:
{
"sub": "user-uuid",
"iss": "https://api.example.com",
"aud": "web-app",
"role": "admin",
"permissions": ["order:read", "order:write"],
"iat": 1700000000,
"exp": 1700086400,
"jti": "unique-token-id"
}
Rules:
- Asymmetric signing (RS256/ES256) for multi-service architectures. Symmetric (HS256) only for single-service monoliths.
- Claims are minimal: subject, role, issued-at, expires. No secrets or PII in claims.
- Access token expiry: 15 minutes. Refresh token expiry: 7 days.
- Refresh token is single-use. Rotate on every refresh.
Step 3: Refresh Token Flow
1. Client sends access_token + refresh_token
2. Server validates signature and expiry of both
3. If access_token expired but refresh_token valid:
a. Issue new access_token (15 min)
b. Rotate refresh_token (issue new, invalidate old)
c. Return both
4. If a consumed refresh_token is reused:
a. Invalidate ALL refresh tokens for that user
b. Log security event
c. Require re-authentication
Implementation:
interface TokenPair {
accessToken: string;
refreshToken: string;
}
async function refreshTokens(refreshToken: string): Promise<TokenPair> {
const stored = await tokenRepository.findByToken(refreshToken);
if (!stored || stored.consumedAt) {
// Token reuse detected
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/auth-oauth2.md
- references/auth-passwordless.md
- references/auth-patterns-advanced.md
- references/auth-patterns-fundamentals.md
- references/auth-patterns-provider-comparison.md
- references/auth-testing.md
- references/jwt-oauth-guide.md
- references/oidc-flows.md
- references/rbac-abac.md
FAQ
Что делает скилл backend-auth-patterns?
Use when the user asks about authentication, JWT login with refresh tokens, sessions, OAuth 2.0 / OIDC login, password hashing, MFA, passwordless or refresh token rotation. Produces server-side auth flows. Not for roles and permissions (use backend-authorization) or browser login UI (use frontend-authentication).
Как установить скилл backend-auth-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл backend-auth-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…