Logo von Backend Auth Patterns

Backend Auth Patterns

Community
j4flmao
backend-auth-patterns

Use this skill when the user says 'auth', 'authentication', 'authorization', 'JWT', 'OAuth', 'RBAC', 'permissions', 'login', 'session', 'refresh token', 'guard', 'middleware auth', or when implementing or reviewing authentication and authorization. This skill enforces: JWT structure and validation, refresh token rotation, OAuth2/OIDC flows, RBAC vs ABAC decision, middleware placement, and password security. Applies to any backend stack. Do NOT use for: specific OAuth provider implementation details, frontend auth UI, or passwordless login flows.

Übersicht

Herausgeberj4flmao
Repositoryagent-skills
Skill-Namebackend-auth-patterns
Sterne
41
Forks
6
Mitgelieferte Dateien
9
LizenzMIT
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • 9 mitgelieferte Dateien

    Skripte, Vorlagen und Referenzmaterial, die das Modell bei der Arbeit lesen kann. Die Dateien sind schreibgeschützt und werden niemals ausgeführt.

  • Open Source

    Von j4flmao auf GitHub veröffentlicht. Prüfen Sie den Quellinhalt vor der Installation.

Installation

Installieren Sie den KI-Skill Backend Auth Patterns in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner — liest SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/auth-patterns
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill anlegen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format lesen kann, kann diesen Skill nutzen — kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/auth-patterns .claude/skills/backend-auth-patterns
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Backend Auth Patterns in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Backend Auth Patterns automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Backend Auth Patterns nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Keys.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

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 TypeStrategyToken TypeStorage
SPA (browser)JWT + Refresh TokenAccess in memory, Refresh in httpOnly cookieMemory + Cookie
Mobile appJWT + Refresh TokenBoth in secure storageKeychain/Keystore
M2M serviceAPI Key or Client CredentialsStatic key or short-lived JWTEnv/Secrets
Server-rendered appSession + CookieSession ID in signed cookieRedis store
Third-party loginOAuth2 / OIDCDelegated to providerProvider-managed
Enterprise SSOOIDC with SAMLDelegated to IdPIdP-managed

Step 2: JWT Implementation

Token claims (minimum):

json
{
  "sub": "user-uuid",
  "role": "admin",
  "iat": 1700000000,
  "exp": 1700086400
}

Common extended claims:

json
{
  "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:

typescript
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
    await tokenRepository.consumeAllForUser(stored?.userId);
    await securityLogger.log('refresh_token_reuse', { token: refreshToken });
    throw new UnauthorizedError('Token reuse detected. All sessions invalidated.');
  }

  if (stored.expiresAt < new Date()) {
    throw new UnauthorizedError('Refresh token expired.');
  }

  await tokenRepository.markConsumed(refreshToken);

  const user = await userRepository.findById(stored.userId);
  const accessToken = generateAccessToken(user);
  const newRefreshToken = generateRefreshToken(user);

  await tokenRepository.save({
    token: newRefreshToken,
    userId: user.id,
    expiresAt: addDays(new Date(), 7),
  });

  return { accessToken, refreshToken: newRefreshToken };
}

Step 4: Authorization Model

RBAC (Role-Based Access Control) — default for most applications:

typescript
const ROLES = {
  admin: ['*'],
  manager: ['order:read', 'order:write', 'user:read'],
  user: ['order:read', 'order:write'],
  guest: ['order:read'],
} as const;

function authorize(requiredPermission: string) {
  return (req: Request, res: Response, next: NextFunction) => {
    const user = req.user;
    const permissions = ROLES[user.role] || [];
    if (!permissions.includes('*') && !permissions.includes(requiredPermission)) {
      throw new ForbiddenError('Insufficient permissions');
    }
    next();
  };
}

ABAC (Attribute-Based Access Control) — for fine-grained control:

python
POLICIES = [
    {
        "effect": "allow",
        "action": "order:read",
        "condition": lambda user, resource, env:
            user.tenant_id == resource.tenant_id
    },
    {
        "effect": "allow",
        "action": "order:delete",
        "condition": lambda user, resource, env:
            user.role == "admin" or resource.created_by == user.id
    }
]

def check_abac(user, action, resource):
    for policy in POLICIES:
        if policy["action"] == action and policy["condition"](user, resource, None):
            return True
    return False

Step 5: Auth Middleware

Auth middleware belongs in Infrastructure layer. Not in Domain. Not in Application.

typescript
// Express middleware
import jwt from 'jsonwebtoken';

function authenticate(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    throw new UnauthorizedError('Missing or invalid authorization header');
  }

  const token = authHeader.substring(7);
  try {
    const payload = jwt.verify(token, process.env.JWT_PUBLIC_KEY, {
      algorithms: ['RS256'],
      issuer: process.env.JWT_ISSUER,
    });
    req.user = payload;
    next();
  } catch (err) {
    if (err instanceof jwt.TokenExpiredError) {
      throw new UnauthorizedError('Token expired');
    }
    throw new UnauthorizedError('Invalid token');
  }
}

Python FastAPI middleware:

python
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt

security = HTTPBearer()

async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    try:
        payload = jwt.decode(
            token,
            PUBLIC_KEY,
            algorithms=["RS256"],
            issuer="https://api.example.com",
            audience="web-app",
        )
        return payload
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")

Step 6: Password Security

typescript
import { hash, compare } from 'bcrypt';

const SALT_ROUNDS = 12;

export async function hashPassword(plain: string): Promise<string> {
  return hash(plain, SALT_ROUNDS);
}

export async function verifyPassword(plain: string, hashed: string): Promise<boolean> {
  return compare(plain, hashed);
}

// Argon2 alternative (preferred for new projects)
import * as argon2 from 'argon2';

export async function hashPasswordArgon2(plain: string): Promise<string> {
  return argon2.hash(plain, {
    type: argon2.argon2id,
    memoryCost: 19456,
    timeCost: 2,
    parallelism: 1,
  });
}

Step 7: Rate Limiting Auth Endpoints

typescript
const AUTH_RATE_LIMITS = {
  login: { window: '5 minutes', max: 5 },
  register: { window: '60 minutes', max: 2 },
  refresh: { window: '1 minute', max: 10 },
  passwordReset: { window: '60 minutes', max: 3 },
};

import rateLimit from 'express-rate-limit';

const loginLimiter = rateLimit({
  windowMs: 5 * 60 * 1000,
  max: 5,
  standardHeaders: true,
  legacyHeaders: false,
  message: { code: 'RATE_LIMITED', message: 'Too many login attempts. Try again later.' },
  keyGenerator: (req) => `${req.ip}-${req.body?.email}`, // Per-IP + per-user
});

app.use('/api/auth/login', loginLimiter);

Step 8: Session Management (Server-Rendered Apps)

typescript
import session from 'express-session';
import RedisStore from 'connect-redis';

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET,
  name: 'sid',
  cookie: {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge: 24 * 60 * 60 * 1000, // 24 hours
  },
  resave: false,
  saveUninitialized: false,
  rolling: true, // Reset maxAge on each request
}));

// Regenerate session ID on login (prevents session fixation)
req.session.regenerate((err) => {
  req.session.userId = user.id;
  req.session.role = user.role;
});

Production Considerations

Token Blacklisting

For immediate revocation of JWTs, maintain a token blacklist:

typescript
// Store in Redis with TTL matching token expiry
async function revokeToken(jti: string, exp: number): Promise<void> {
  const ttl = exp - Math.floor(Date.now() / 1000);
  await redis.set(`revoked:${jti}`, 'true', 'EX', Math.max(ttl, 60));
}

async function isTokenRevoked(jti: string): Promise<boolean> {
  return (await redis.exists(`revoked:${jti}`)) === 1;
}

OAuth2 Flows Selection

FlowUse CaseSecurity
Authorization CodeWeb apps with backendBest — PKCE required
Authorization Code + PKCESPA, mobileRequired for native apps
Client CredentialsM2M serviceNo user context
Resource Owner PasswordLegacy / trusted appsAvoid — exposes credentials
ImplicitLegacy SPAsDeprecated — use PKCE

Anti-Patterns

  1. Storing tokens in localStorage: XSS vulnerability. Use httpOnly cookies for SPA.
  2. Not validating token signature: Accepting any JWT without verification.
  3. Ignoring token expiry: Never trust client-side expiry. Always verify exp server-side.
  4. Refresh token without rotation: Static refresh tokens never changed. If stolen, permanent access.
  5. No rate limiting on auth endpoints: Allows brute force password guessing.
  6. Logging passwords in plaintext: Mask or exclude sensitive fields.
  7. JWT with user data in claims: PII in JWT claims exposed to all services.
  8. Secret hardcoded in source: Always use environment variables or secrets manager.
  9. Session fixation not prevented: Regenerate session ID on login.
  10. Missing CSRF protection for cookie-based auth: SameSite=Strict mitigates most cases.
  11. Rolling your own crypto: Always use standard libraries (bcrypt, argon2, jose).
  12. Overly long-lived access tokens: Keep to 15 minutes max.

Security Considerations

Headers for Auth Endpoints

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Cache-Control: no-store  (never cache auth responses)

Brute Force Prevention

  • IP-based rate limiting on login endpoint
  • Account lockout after 5 failed attempts (temporary, 15 min)
  • Progressive delay on repeated failures
  • CAPTCHA after threshold
  • Alert on account take-over patterns (many IPs, one user)

Audit Logging for Auth

  • Log every authentication attempt (success/failure)
  • Log token refresh, revocation, role changes
  • Log password changes and reset requests
  • Never log passwords, tokens, or secrets

Comparative Analysis

FeatureJWT + RefreshSession CookiesOAuth2 / OIDC
Stateful/StatelessStateless (access), Stateful (refresh)StatefulStateless
ScalabilityExcellentRequires shared session storeExcellent
XSS protectionRequires httpOnly cookiehttpOnly cookieDelegated
CSRF protectionVia configurationVia tokensVia state param
Mobile supportNativeRequires webviewNative SDK
Token revocationBlacklist requiredImmediatePer-provider
Implementation complexityModerateLowHigh

Performance Considerations

  • Token verification: HS256 ~0.01ms, RS256 ~0.1ms, ES256 ~0.05ms per verification
  • bcrypt verification: ~10ms per attempt (cost=12). Rate limiting mitigates attack surface.
  • Session lookup: Redis <1ms. Use connection pooling.
  • Token blacklist: Store in Redis with TTL. Bloom filter for high-traffic.
  • API key lookup: Hash keys before storing. Constant-time comparison.

Tooling

ToolPurpose
jsonwebtoken / joseJWT creation and verification
bcrypt / argon2Password hashing
express-rate-limitRate limiting middleware
helmetHTTP security headers
connect-redisRedis session store
passport.jsStrategy-based auth middleware
keycloak-connectKeycloak integration
auth0Auth0 integration SDK

Rules

  • Never store plaintext passwords. Always hash with bcrypt (cost >= 10) or argon2id.
  • JWTs are short-lived. 15 minutes for access tokens. 7 days maximum for refresh tokens.
  • Every request is validated server-side. Client is never trusted for identity.
  • For browser apps: use httpOnly, Secure, SameSite=Strict cookies for refresh tokens.
  • Log every auth failure with: timestamp, user ID, IP address, failure reason.
  • Brute force protection on login is mandatory. Account lockout after 5 failures.
  • Refresh tokens are single-use with rotation. Token reuse detection invalidates all.
  • Auth middleware belongs in Infrastructure layer.
  • Secrets are always from environment variables or secrets manager.
  • Authorization decisions based on permissions, never on role names directly.
  • CSRF protection for all cookie-based authentication.
  • Password reset tokens expire in 15 minutes and are single-use.

References

  • references/auth-oauth2.md — OAuth2 Flows
  • references/auth-passwordless.md — Passwordless Authentication
  • references/auth-testing.md — Authentication Testing
  • references/jwt-oauth-guide.md — JWT and OAuth Guide
  • references/oidc-flows.md — OIDC Flows
  • references/rbac-abac.md — RBAC vs ABAC
  • references/auth-patterns-fundamentals.md — Auth Patterns Fundamentals
  • references/auth-patterns-advanced.md — Auth Patterns Advanced
  • references/auth-patterns-provider-comparison.md — Auth Provider Comparison

Handoff

No artifact produced. Next skill: backend-testing — test auth flows, verify auth middleware, test rate limiting. Carry forward: auth strategy, token structure, authorization model, middleware implementation details.

  • Review code for security, performance, and correctness before merging.

Mitgelieferte Dateien

Das Modell liest diese Dateien bei Bedarf, während der Skill geladen ist. Sie werden als lesbare Dateien bereitgestellt und niemals ausgeführt.

Häufig gestellte Fragen

Was macht der KI-Skill Backend Auth Patterns?

Use this skill when the user says 'auth', 'authentication', 'authorization', 'JWT', 'OAuth', 'RBAC', 'permissions', 'login', 'session', 'refresh token', 'guard', 'middleware auth', or when implementing or reviewing authentication and authorization. This skill enforces: JWT structure and validation, refresh token rotation, OAuth2/OIDC flows, RBAC vs ABAC decision, middleware placement, and password security. Applies to any backend stack. Do NOT use for: specific OAuth provider implementation details, frontend auth UI, or passwordless login flows.

Warum Backend Auth Patterns in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Backend Auth Patterns besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Backend Auth Patterns in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/auth-patterns ein. TypingMind liest die Datei SKILL.md, bündelt die zugehörigen Dateien und installiert alles als Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Backend Auth Patterns nutzen?

Jedes Modell, das Sie in TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Backend Auth Patterns verwenden?

So viele Sie möchten. Solange ein Modell Skills unterstützt, können Sie Backend Auth Patterns damit verwenden – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama und weitere – alles in TypingMind mit Ihren eigenen API-Schlüsseln.

Ist der KI-Skill Backend Auth Patterns kostenlos?

Ja. Der Skill wird von j4flmao auf GitHub unter der Lizenz MIT veröffentlicht. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: eine Datei namens SKILL.md mit einem Namen und einer Beschreibung sowie allen Skripten, Vorlagen oder Referenzdateien, die das Modell möglicherweise benötigt. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und benötigen daher weder Server noch API-Schlüssel oder Laufzeitumgebung. Sie funktionieren mit jedem Modell.

Alle

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇