auth-implementation
Implement authentication and authorization in web applications. Use when adding login, signup, sessions, JWT tokens, OAuth, SSO, API key auth, role-based access control (RBAC), permissions, protected routes, middleware guards, password hashing, MFA/2FA, refresh token rotation, CSRF protection, or integrating auth providers like NextAuth/Auth.js, Better Auth, Lucia, Clerk, Auth0, Supabase Auth, Firebase Auth, Passport.js. Covers Next.js, Express, Fastify, Django, FastAPI, Laravel, Go. Handles database schema design, security hardening, and common auth pitfalls (token storage, session fixation, CORS).
What this skill does
# Auth Implementation
Comprehensive guide for implementing authentication and authorization in web applications. Covers session-based auth, JWT, OAuth 2.0, SSO, API keys, RBAC/ABAC, and security hardening across all major frameworks and libraries.
## Decision Matrix
Use this table to pick the right approach and library for your stack:
| Use Case | Framework | Recommended Approach | Library | Reference |
|----------|-----------|---------------------|---------|-----------|
| Full-stack app, social login | Next.js App Router | OAuth + sessions | Auth.js v5 | [NEXTAUTH-AUTHJS.md](references/NEXTAUTH-AUTHJS.md) |
| Full-stack app, email/password + social | Next.js / SvelteKit | Session-based | Better Auth | [BETTER-AUTH.md](references/BETTER-AUTH.md) |
| Full-stack, maximum control | Next.js / SvelteKit / Astro | Session-based | Lucia v3 | [LUCIA-AUTH.md](references/LUCIA-AUTH.md) |
| API backend, social login | Express / Fastify | Strategy-based | Passport.js | [PASSPORT-EXPRESS.md](references/PASSPORT-EXPRESS.md) |
| Microservice API | Any | JWT (access + refresh) | jose / jsonwebtoken | [CUSTOM-JWT.md](references/CUSTOM-JWT.md) |
| SaaS, managed auth | Any | Hosted OAuth/OIDC | Clerk / Auth0 / Supabase Auth | [OAUTH-OIDC.md](references/OAUTH-OIDC.md) |
| Django app | Django | Session-based | django.contrib.auth + allauth | [FRAMEWORK-PATTERNS.md](references/FRAMEWORK-PATTERNS.md) |
| Python API | FastAPI | JWT / OAuth2 | python-jose + Depends() | [FRAMEWORK-PATTERNS.md](references/FRAMEWORK-PATTERNS.md) |
| PHP app | Laravel | Session / token | Sanctum / Fortify / Breeze | [FRAMEWORK-PATTERNS.md](references/FRAMEWORK-PATTERNS.md) |
| Go service | net/http / Chi / Gin | Session or JWT | gorilla/sessions / golang-jwt | [FRAMEWORK-PATTERNS.md](references/FRAMEWORK-PATTERNS.md) |
| Enterprise SSO | Any | SAML / OIDC | Provider-specific SDK | [OAUTH-OIDC.md](references/OAUTH-OIDC.md) |
| Machine-to-machine | Any | API keys or Client Credentials | Custom | [CUSTOM-JWT.md](references/CUSTOM-JWT.md) |
| Need RBAC/permissions | Any | Role-permission model | CASL / Casbin / custom | [RBAC-ABAC.md](references/RBAC-ABAC.md) |
## Implementation Workflow
Follow these 5 steps for any auth implementation:
### Step 1: Detect Stack
Read `package.json`, `requirements.txt`, `go.mod`, `composer.json`, or framework config to identify:
- Framework and version (Next.js 14+, Express, Django, FastAPI, Laravel, Go, SvelteKit)
- Database and ORM (Prisma, Drizzle, SQLAlchemy, GORM, Eloquent)
- Existing auth code (check for auth middleware, session config, JWT imports)
### Step 2: Choose Approach
Use the Decision Matrix above. Key factors:
- **Server-rendered app** → session-based (cookies)
- **SPA + API** → JWT (access + refresh tokens) or BFF pattern
- **Mobile + API** → JWT with secure token storage
- **Multiple providers needed** → Auth.js, Better Auth, or Passport.js
- **Enterprise / compliance** → managed provider (Clerk, Auth0) or OIDC
- **Maximum control** → Lucia or custom JWT
### Step 3: Database Schema
Set up auth tables. See [DATABASE-SCHEMAS.md](references/DATABASE-SCHEMAS.md) for full schemas.
Core tables needed:
- `users` — id, email, password_hash, email_verified, created_at
- `sessions` — id, user_id, expires_at (for session-based)
- `accounts` — id, user_id, provider, provider_account_id (for OAuth)
### Step 4: Implement
Use the relevant reference file for step-by-step implementation. Install dependencies, configure auth, add routes, protect endpoints.
### Step 5: Harden
Apply [SECURITY-CHECKLIST.md](references/SECURITY-CHECKLIST.md). At minimum:
- [ ] CSRF protection enabled
- [ ] Cookies: HttpOnly, Secure, SameSite=Lax
- [ ] Password hashing: argon2id or bcrypt
- [ ] Rate limiting on login/register/reset
- [ ] Input validation on all auth endpoints
## Session-Based Auth (Quick Start)
Session-based auth stores session ID in a cookie. Server holds session data.
**When to use:** Server-rendered apps, full-stack frameworks, when you need easy revocation.
### Express + express-session
```typescript
import session from 'express-session';
import RedisStore from 'connect-redis';
import { createClient } from 'redis';
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET!, // min 32 chars, random
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
sameSite: 'lax',
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
},
}));
```
### Next.js (iron-session)
```typescript
// lib/session.ts
import { getIronSession } from 'iron-session';
import { cookies } from 'next/headers';
export async function getSession() {
return getIronSession<SessionData>(await cookies(), {
password: process.env.SESSION_SECRET!,
cookieName: 'app-session',
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
sameSite: 'lax',
},
});
}
```
## JWT Auth (Quick Start)
JWT auth uses signed tokens. Access token (short-lived) + refresh token (long-lived).
**When to use:** APIs consumed by SPAs, mobile apps, microservices. See [CUSTOM-JWT.md](references/CUSTOM-JWT.md).
### Token Architecture
```
Access Token: Short-lived (15 min), in memory or Authorization header
Refresh Token: Long-lived (7-30 days), HttpOnly cookie, rotated on use
```
### Node.js (jose library)
```typescript
import { SignJWT, jwtVerify } from 'jose';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
// Create access token
async function createAccessToken(userId: string, role: string) {
return new SignJWT({ sub: userId, role })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('15m')
.sign(secret);
}
// Verify token
async function verifyToken(token: string) {
const { payload } = await jwtVerify(token, secret);
return payload;
}
```
### Middleware Pattern
```typescript
async function authMiddleware(req: Request, next: Function) {
const token = req.headers.get('Authorization')?.replace('Bearer ', '');
if (!token) return new Response('Unauthorized', { status: 401 });
try {
const payload = await verifyToken(token);
req.user = payload;
return next();
} catch {
return new Response('Invalid token', { status: 401 });
}
}
```
## OAuth 2.0 / Social Login (Quick Start)
OAuth lets users sign in with existing accounts (Google, GitHub, etc.).
**Flow: Authorization Code + PKCE** (recommended for all clients):
```
1. Client generates code_verifier + code_challenge
2. Redirect to provider: /authorize?response_type=code&code_challenge=...
3. User authenticates with provider
4. Provider redirects back with authorization code
5. Server exchanges code + code_verifier for tokens
6. Server creates session or issues own JWT
```
See [OAUTH-OIDC.md](references/OAUTH-OIDC.md) for provider-specific setup.
## Provider Quick Reference
| Provider | Install | Config Needed | Reference |
|----------|---------|---------------|-----------|
| Auth.js v5 | `npm i next-auth@beta` | `auth.ts` + providers + adapter | [NEXTAUTH-AUTHJS.md](references/NEXTAUTH-AUTHJS.md) |
| Better Auth | `npm i better-auth` | `auth.ts` + DB + plugins | [BETTER-AUTH.md](references/BETTER-AUTH.md) |
| Lucia v3 | `npm i lucia` | Adapter + session config | [LUCIA-AUTH.md](references/LUCIA-AUTH.md) |
| Passport.js | `npm i passport passport-local` | Strategies + serialize | [PASSPORT-EXPRESS.md](references/PASSPORT-EXPRESS.md) |
| Clerk | `npm i @clerk/nextjs` | `CLERK_*` env vars | [OAUTH-OIDC.md](references/OAUTH-OIDC.md) |
| Auth0 | `npm i @auth0/nextjs-auth0` | `AUTH0_*` env vars | [OAUTH-OIDC.md](references/OAUTH-OIDC.md) |
| Supabase Auth | `npm i @supabase/supabase-js` | Supabase project URL + key | [OAUTH-OIDC.md](references/OAUTH-OIDC.md) |
| Firebase Auth | `npm i firebase` | FirebaRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.