Mmcp.market

authentication-patterns skill

by zebbern·zebbern/claude-code-guide·4.6k stars·MIT

Authentication patterns: session vs JWT vs OAuth comparison, provider selection (NextAuth, Clerk, Supabase Auth), security checklist, and common mistakes. Use when implementing auth, reviewing auth flows, or choosing auth providers.

A100/100content scan

Is the authentication-patterns skill safe?

Clean: nothing in its files matched our rules. We read 1 file in the folder on 2026-09-28.

No findings.

Install the authentication-patterns skill

A skill is a folder. Copy it into your agent's skills folder and the agent loads it when the task matches its description.

git clone --depth 1 https://github.com/zebbern/claude-code-guide.git /tmp/claude-code-guide
mkdir -p ~/.claude/skills
cp -r /tmp/claude-code-guide/skills/authentication-patterns ~/.claude/skills/authentication-patterns
available in every project

In the Claude apps, zip the folder and upload it from the Skills settings. The folder on GitHub

The instructions your agent would load

SKILL.md as published, without the frontmatter. Read it on GitHub

Authentication Patterns Skill

Reference for implementing secure, production-ready authentication.

WHENTOUSE

Apply this skill when implementing authentication in a project, reviewing existing auth flows for security issues, choosing between auth providers, or migrating between auth strategies. Use the security checklist before shipping any auth-related change.

AUTH_APPROACHES

Decision Guide

  • Server-rendered app with simple needs → Session-based
  • SPA or mobile app calling APIs → JWT with refresh token rotation
  • Want social login or SSO → OAuth 2.0 / OIDC
  • Greenfield with modern UX goals → Passkeys + OAuth fallback

JWTBESTPRACTICES

Token Lifecycle

Login → Access Token (short-lived) + Refresh Token (long-lived, rotated)
  │
  ├─ Access Token: 15 min expiry, sent via httpOnly cookie or Authorization header
  │
  └─ Refresh Token: 7-30 day expiry, stored in httpOnly secure cookie
       │
       └─ On use: issue new access + new refresh token, invalidate old refresh token

Rules

  • [P0-MUST] Set short expiry on access tokens (15 minutes or less).
  • [P0-MUST] Store tokens in httpOnly, Secure, SameSite=Lax cookies — never in localStorage or sessionStorage.
  • [P0-MUST] Implement refresh token rotation — each refresh token is single-use.
  • [P0-MUST] Maintain a server-side blocklist for revoked refresh tokens.
  • [P1-SHOULD] Include only essential claims in JWT payload (sub, iat, exp, role). Keep it small.
  • [P1-SHOULD] Use asymmetric signing (RS256 or ES256) for distributed systems; symmetric (HS256) for single-service only.
  • [P1-SHOULD] Validate iss, aud, and exp claims on every request.
  • [P2-MAY] Use JWE (encrypted JWT) when token payload contains sensitive data.

Token Storage Comparison

PROVIDER_PATTERNS

Comparison

When to Use Each

  • NextAuth / Auth.js: You want provider flexibility, self-hosting, and database session control. Best when you need custom flows.
  • Clerk: You want auth done fast with pre-built UI components. Best for MVPs and teams that don't want to build auth UI.
  • Supabase Auth: You're already using Supabase. Auth integrates with RLS policies for row-level security.
  • Lucia: You want a minimal, type-safe session library without framework lock-in.

NextAuth.js Setup Pattern

// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GitHub({
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    }),
  ],
  callbacks: {
    session({ session, user }) {
      session.user.id = user.id;
      return session;
    },
  },
});

SECURITY_CHECKLIST

Before Shipping Auth

  • [ ] Rate limiting: Login endpoint limited to 5-10 attempts per minute per IP.
  • [ ] CSRF protection: Anti-CSRF tokens on all state-changing requests (or use SameSite=Lax cookies).
  • [ ] Password hashing: Using bcrypt (cost 12+) or argon2id — never MD5, SHA-1, or plain SHA-256.
  • [ ] HTTPS only: All auth endpoints served over TLS. Cookies have Secure flag.
  • [ ] Input validation: Email format, password length (min 8, max 128), no SQL/NoSQL injection vectors.
  • [ ] Account enumeration: Login and registration return the same response whether account exists or not.
  • [ ] Session invalidation: Logout invalidates server-side session/refresh token, not just client cookie.
  • [ ] MFA support: TOTP (authenticator app) or WebAuthn as second factor for sensitive accounts.
  • [ ] Password reset: Time-limited tokens (1 hour), single-use, sent over secure channel.
  • [ ] Audit logging: Log auth events (login, logout, failed attempts, password changes) with timestamp and IP.

Password Hashing

// Using bcrypt
import bcrypt from "bcrypt";

const SALT_ROUNDS = 12;

async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, SALT_ROUNDS);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}
// Using argon2 (preferred for new projects)
import argon2 from "argon2";

async function hashPassword(password: string): Promise<string> {
  return argon2.hash(password, { type: argon2.argon2id });
}

async function verifyPassword(hash: string, password: string): Promise<boolean> {
  return argon2.verify(hash, password);
}

COMMON_MISTAKES

More skills from zebbern/claude-code-guide

  • Aacademic-paper-reviewerSimulates academic peer review, evaluating papers across Originality, Methodology, Results, and Writing to provide Major/Minor Revision recommendations with actionable feedback. Triggers when a user asks to \"review my paper,\" \"simulate peer review,\" or \"give my paper a peer review.
  • Aactive-directory-attacksThis skill should be used when the user asks to "attack Active Directory", "exploit AD", "Kerberoasting", "DCSync", "pass-the-hash", "BloodHound enumeration", "Golden Ticket", "Silver Ticket", "AS-REP roasting", "NTLM relay", or needs guidance on Windows domain penetration testing.
  • Capi-fuzzing-bug-bountyThis skill should be used when the user asks to "test API security", "fuzz APIs", "find IDOR vulnerabilities", "test REST API", "test GraphQL", "API penetration testing", "bug bounty API testing", or needs guidance on API security assessment techniques.
  • Aapi-shape-explorerGenerate multiple radically different interface designs for a module using parallel sub-agents. Use when user wants to design an API, explore interface options, compare module shapes, or mentions "design it twice".
  • Aaudit-flowInteractive system flow tracing across CODE, API, AUTH, DATA, NETWORK layers with SQLite persistence and Mermaid export. Use for security audits, compliance documentation, flow tracing, feature ideation, brainstorming, debugging, architecture reviews, or incident post-mortems. Triggers on audit, trace flow, document flow, security review, debug flow, brainstorm, architecture review, post-mortem, incident review.
  • Aaws-penetration-testingThis skill should be used when the user asks to "pentest AWS", "test AWS security", "enumerate IAM", "exploit cloud infrastructure", "AWS privilege escalation", "S3 bucket testing", "metadata SSRF", "Lambda exploitation", or needs guidance on Amazon Web Services security assessment.
  • Abroken-authenticationThis skill should be used when the user asks to "test for broken authentication vulnerabilities", "assess session management security", "perform credential stuffing tests", "evaluate password policies", "test for session fixation", or "identify authentication bypass flaws". It provides comprehensive techniques for identifying authentication and session management weaknesses in web applications.
  • Cburp-suite-testingThis skill should be used when the user asks to "intercept HTTP traffic", "modify web requests", "use Burp Suite for testing", "perform web vulnerability scanning", "test with Burp Repeater", "analyze HTTP history", or "configure proxy for web testing". It provides comprehensive guidance for using Burp Suite's core features for web application security testing.
  • AcachingCaching strategies — invalidation, TTL guidelines, cache keys, cache layers, and when not to cache. Use when implementing or reviewing caching logic.
  • Achart-imageGenerate publication-quality PNG chart images from data, supporting line, bar, area, candlestick, pie, and heatmap charts. Triggers when the user asks to visualize data, create a graph, plot a time series, or generate a chart for a report, alert, or dashboard. Runs as a lightweight, headless Node.js process without a browser.
  • Dcloud-penetration-testingThis skill should be used when the user asks to "perform cloud penetration testing", "assess Azure or AWS or GCP security", "enumerate cloud resources", "exploit cloud misconfigurations", "test O365 security", "extract secrets from cloud environments", or "audit cloud infrastructure". It provides comprehensive techniques for security assessment across major cloud platforms.
  • Acode-documenterUse when adding docstrings, creating API documentation, or building documentation sites. Invoke for OpenAPI/Swagger specs, JSDoc, doc portals, tutorials, user guides.

All agent skills → · MCP servers