authentication-patterns
OAuth 2.0, JWT, SSO, MFA, NextAuth/Clerk/Supabase Auth implementation patterns
What this skill does
# Authentication Patterns
## Overview
This skill covers authentication and authorization implementation across web and mobile applications. It addresses OAuth 2.0 flows (Authorization Code with PKCE, Client Credentials), JWT management (access tokens, refresh tokens, rotation), session management strategies, multi-factor authentication (TOTP, WebAuthn/passkeys), integration with auth libraries (NextAuth/Auth.js v5, Clerk, Supabase Auth, Lucia), SSO protocols (SAML, OIDC), and authorization patterns (RBAC, ABAC).
Use this skill when building login/signup flows, integrating social login providers, implementing MFA, setting up SSO for enterprise customers, designing authorization models, or migrating between auth providers.
---
## Core Principles
1. **Never roll your own crypto** - Use established libraries for password hashing (bcrypt, argon2), JWT signing, and OAuth flows. Custom auth code is the #1 source of security vulnerabilities in web applications.
2. **Defense in depth** - Authentication is not a single check. Layer session validation, CSRF protection, rate limiting, and anomaly detection. Assume every layer can be bypassed individually.
3. **Tokens are credentials** - Access tokens, refresh tokens, and session cookies must be stored securely (httpOnly cookies, encrypted storage), transmitted over HTTPS only, and rotated regularly.
4. **Least privilege by default** - Users and API clients should start with minimal permissions. Elevate access through explicit role assignment, never through implicit trust.
5. **Plan for account recovery** - Password reset, MFA recovery codes, email verification, and account lockout all need designed flows. These are more complex than the happy-path login.
---
## Key Patterns
### Pattern 1: NextAuth (Auth.js v5) with OAuth and Database Sessions
**When to use:** Next.js applications needing social login, email/password, or magic link authentication with server-side session management.
**Implementation:**
```typescript
// auth.ts - Auth.js v5 configuration
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import Credentials from "next-auth/providers/credentials";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import { verifyPassword } from "@/lib/password";
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
GitHub({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
Google({
clientId: process.env.GOOGLE_ID!,
clientSecret: process.env.GOOGLE_SECRET!,
}),
Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const user = await prisma.user.findUnique({
where: { email: credentials.email as string },
});
if (!user?.passwordHash) return null;
const valid = await verifyPassword(
credentials.password as string,
user.passwordHash
);
if (!valid) return null;
return { id: user.id, email: user.email, name: user.name };
},
}),
],
session: {
strategy: "database", // Server-side sessions (not JWT)
maxAge: 30 * 24 * 60 * 60, // 30 days
updateAge: 24 * 60 * 60, // Refresh session every 24 hours
},
callbacks: {
async session({ session, user }) {
// Add user role to session
session.user.id = user.id;
session.user.role = user.role;
return session;
},
async signIn({ user, account }) {
// Block sign-in for disabled accounts
if (user.id) {
const dbUser = await prisma.user.findUnique({
where: { id: user.id },
});
if (dbUser?.disabled) return false;
}
return true;
},
},
pages: {
signIn: "/login",
error: "/auth/error",
verifyRequest: "/auth/verify",
},
});
```
```typescript
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
```
```typescript
// Middleware for route protection
// middleware.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
export default auth((req) => {
const isLoggedIn = !!req.auth;
const isAuthPage = req.nextUrl.pathname.startsWith("/login") ||
req.nextUrl.pathname.startsWith("/register");
const isDashboard = req.nextUrl.pathname.startsWith("/dashboard");
if (isDashboard && !isLoggedIn) {
return NextResponse.redirect(new URL("/login", req.url));
}
if (isAuthPage && isLoggedIn) {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
return NextResponse.next();
});
export const config = {
matcher: ["/dashboard/:path*", "/login", "/register"],
};
```
**Why:** Auth.js v5 handles OAuth complexity (state parameters, PKCE, token exchange), session management, CSRF protection, and provider-specific quirks. Database sessions are more secure than JWT sessions because they can be revoked instantly and don't expose claims to the client.
---
### Pattern 2: JWT Access/Refresh Token Pattern
**When to use:** API authentication for SPAs, mobile apps, or microservice-to-microservice communication where stateless verification is needed.
**Implementation:**
```typescript
// Token generation
import jwt from "jsonwebtoken";
import { randomBytes } from "crypto";
interface TokenPayload {
sub: string; // User ID
email: string;
role: string;
}
interface TokenPair {
accessToken: string;
refreshToken: string;
expiresIn: number;
}
const ACCESS_TOKEN_EXPIRY = "15m";
const REFRESH_TOKEN_EXPIRY = "7d";
function generateTokenPair(user: TokenPayload): TokenPair {
const accessToken = jwt.sign(
{ sub: user.sub, email: user.email, role: user.role },
process.env.JWT_SECRET!,
{
expiresIn: ACCESS_TOKEN_EXPIRY,
issuer: "myapp",
audience: "myapp-api",
}
);
// Refresh token is opaque (not JWT) - stored server-side
const refreshToken = randomBytes(64).toString("hex");
return {
accessToken,
refreshToken,
expiresIn: 900, // 15 minutes in seconds
};
}
// Token refresh endpoint
async function refreshTokens(refreshToken: string): Promise<TokenPair> {
// 1. Look up refresh token in database
const stored = await db.refreshToken.findUnique({
where: { token: hashToken(refreshToken) },
include: { user: true },
});
if (!stored || stored.expiresAt < new Date()) {
throw new UnauthorizedError("Invalid or expired refresh token");
}
// 2. Rotate refresh token (invalidate old, create new)
await db.refreshToken.delete({ where: { id: stored.id } });
const newPair = generateTokenPair({
sub: stored.user.id,
email: stored.user.email,
role: stored.user.role,
});
// 3. Store new refresh token
await db.refreshToken.create({
data: {
token: hashToken(newPair.refreshToken),
userId: stored.user.id,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
},
});
return newPair;
}
// Token verification middleware
function verifyAccessToken(token: string): TokenPayload {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!, {
issuer: "myapp",
audience: "myapp-api",
});
return decoded as TokenPayload;
} catch (err) {
if (err instanceof jwt.TokenExpiredError) {
throw new UnauthorizedError("Access token expired");
}
throw new UnauthorizedError("Invalid access token");
}
}
```
```typescript
// Secure cookie-based token delivery (for web apps)
function setAuthCookies(res: Response, tokens: TokenPair): void {
// Access token in httpOnly cookie
res.headers.append(
"Set-Cookie",
`access_token=${tokens.accessTokenRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.