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.
npx skills add https://github.com/zebbern/claude-code-guide --skill authentication-patterns
Reference for implementing secure, production-ready authentication.
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.
| Approach | How It Works | Best For | Drawbacks |
|----------|-------------|----------|-----------|
| Session-based | Server stores session in DB/Redis, client holds session ID cookie | Traditional server-rendered apps, apps needing instant revocation | Requires server-side storage, harder to scale horizontally without shared store |
| JWT (stateless) | Server signs token, client sends it on each request | API-first apps, microservices, mobile clients | Cannot revoke without blocklist, token size grows with claims |
| OAuth 2.0 / OIDC | Delegates auth to external provider (Google, GitHub, etc.) | Social login, enterprise SSO, reducing auth responsibility | More complex flow, depends on external provider availability |
| Passkeys / WebAuthn | Cryptographic key pair, no passwords | High-security apps, passwordless UX | Limited browser support legacy, user education needed |
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
httpOnly, Secure, SameSite=Lax cookies — never in localStorage or sessionStorage.iss, aud, and exp claims on every request.| Storage | XSS Safe | CSRF Safe | Recommendation |
|---------|----------|-----------|----------------|
| httpOnly cookie | Yes | No (needs CSRF token) | Recommended |
| localStorage | No | Yes | Never use for auth tokens |
| sessionStorage | No | Yes | Never use for auth tokens |
| In-memory (JS variable) | Yes | Yes | OK for SPAs, lost on refresh |
| Provider | Type | Best For | Pricing | Key Features |
|----------|------|----------|---------|-------------|
| NextAuth / Auth.js | OSS library | Next.js apps wanting full control | Free | 80+ providers, DB adapters, self-hosted |
| Clerk | Managed service | Fast launch, pre-built UI, user management | Free tier, then per-MAU | Drop-in components, user dashboard, org support |
| Supabase Auth | Managed (part of Supabase) | Apps already using Supabase for DB/storage | Free tier, then per-MAU | Row-level security integration, magic links, SSO |
| Lucia | OSS library | Full control, minimal abstraction | Free | Session-based, framework-agnostic, type-safe |
// 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;
},
},
});
SameSite=Lax cookies).Secure flag.// 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);
}
| Mistake | Risk | Fix |
|---------|------|-----|
| Storing JWT in localStorage | XSS can steal tokens | Use httpOnly cookies |
| Long-lived JWTs (days/weeks) | Stolen token is valid for extended period | 15 min access token + refresh rotation |
| Missing CSRF protection | Attackers can forge requests from other sites | SameSite=Lax cookies + CSRF token |
| Weak password requirements | Brute force and credential stuffing | Min 8 chars, check against breached password lists |
| Exposing user existence on login | Account enumeration | Generic "Invalid credentials" message |
| Not rotating refresh tokens | Stolen refresh token grants indefinite access | Single-use refresh tokens with rotation |
| Hardcoding secrets in source | Credential leak via git history | Use environment variables, never commit secrets |
| Missing rate limiting on login | Brute force attacks | 5-10 attempts/min per IP, exponential backoff |
| Rolling your own crypto | Subtle vulnerabilities | Use established libraries (bcrypt, argon2, jose) |
| Not validating JWT claims | Token misuse across services | Always verify iss, aud, exp |
Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.
This 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.
You are a dependency security expert specializing in vulnerability scanning, license compliance, and supply chain security. Analyze project dependencies for known vulnerabilities, licensing issues, outdated packages, and provide actionable remediation strategies.
Comprehensive Flow Nexus platform management - authentication, sandboxes, app deployment, payments, and challenges
This skill should be used when the user asks to "escalate privileges on Linux", "find privesc vectors on Linux systems", "exploit sudo misconfigurations", "abuse SUID binaries", "exploit cron jobs for root access", "enumerate Linux systems for privilege escalation", or "gain root access from low-privilege shell". It provides comprehensive techniques for identifying and exploiting privilege escalation paths on Linux systems.
Expert malware analyst specializing in defensive malware research, threat intelligence, and incident response. Masters sandbox analysis, behavioral analysis, and malware family identification. Handles static/dynamic analysis, unpacking, and IOC extraction. Use PROACTIVELY for malware triage, threat hunting, incident response, or security research.
This skill should be used when the user asks to "use Metasploit for penetration testing", "exploit vulnerabilities with msfconsole", "create payloads with msfvenom", "perform post-exploitation", "use auxiliary modules for scanning", or "develop custom exploits". It provides comprehensive guidance for leveraging the Metasploit Framework in security assessments.
Expert in secure mobile coding practices specializing in input validation, WebView security, and mobile-specific security patterns. Use PROACTIVELY for mobile security implementations or mobile security code reviews.
Take zebbern/authentication-patterns from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.