Overview
Complete authentication system with multiple sign-in methods, session management, and security best practices. Supports email/password, OAuth providers (Google, GitHub), magic links, and password reset flows.
Use Cases
- SaaS applications: Secure user accounts with subscription management
- Marketplaces: Buyer and seller authentication with role-based access
- Content platforms: User-generated content with moderation roles
When to Use This Pattern
Use this pattern when you need:
- Secure user authentication for your application
- Multiple sign-in options (email, social, passwordless)
- Session management across devices
- Role-based access control (RBAC)
- Password reset and email verification flows
Pro Tips
Critical security considerations:
- Choose your auth provider first - Clerk (easiest), NextAuth (flexible), Supabase (integrated), or custom
- Never store passwords in plain text - Use bcrypt or argon2 with proper salt rounds
- Implement rate limiting - Prevent brute force attacks on login endpoints
- Use HTTPS only - Never send credentials over unencrypted connections
Implementation Phases
Phase 1: Email/Password Authentication
Core authentication flow:
- User registration with email/password
- Hash passwords with bcrypt (12+ salt rounds)
- Email verification (send token, verify within 24 hours)
- Login with credentials
- JWT or session-based auth (choose one)
// Example user schema
model User {
id String @id @default(uuid())
email String @unique
passwordHash String
emailVerified DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Phase 2: OAuth Integration
Add social sign-in providers:
- Google OAuth (most common)
- GitHub OAuth (developer-focused)
- Optional: Apple, Microsoft, Twitter
Implementation notes:
- Register OAuth apps with each provider
- Store OAuth tokens securely
- Handle account linking (same email, different providers)
- Sync profile data (avatar, name) on login
Phase 3: Magic Link Authentication
Passwordless authentication:
- User enters email only
- Send magic link with signed token
- Token expires in 15 minutes
- One-time use (invalidate after click)
- Redirect to app after verification
Why magic links?
- Better UX (no password to remember)
- More secure (no password to steal)
- Higher conversion (faster signup)
Phase 4: Session Management
Secure session handling:
- JWT tokens (stateless) OR database sessions (stateful)
- Refresh token rotation
- Session expiration (7-30 days typical)
- Device tracking (IP, user agent)
- "Sign out all devices" functionality
Edge Cases to Handle
Critical Security Edge Cases
Account enumeration attack:
- Don't reveal if email exists on login errors
- Use same error message: "Invalid credentials"
- Rate limit login attempts per IP
Password reset abuse:
- Rate limit reset requests per email
- Expire tokens after 1 hour
- Invalidate all tokens on successful reset
- Log all reset attempts
Session hijacking:
- Bind sessions to IP/user agent (optional)
- Implement session timeout
- Use httpOnly, secure, sameSite cookies
- Detect suspicious activity (geo-location changes)
OAuth callback vulnerabilities:
- Validate state parameter (CSRF protection)
- Check redirect URI whitelist
- Verify token signatures
- Handle OAuth errors gracefully
Concurrent sessions:
- Allow multiple sessions (default)
- OR enforce single session per user
- Track active sessions in database
- Revoke sessions on password change
Tech Stack Recommendations
Option 1: Clerk (Easiest)
Best for: Startups, MVPs, no-fuss auth
Pros:
- ā Pre-built UI components
- ā Handles everything (OAuth, magic links, sessions)
- ā User management dashboard
- ā Free tier (10k MAU)
Cons:
- ā Less customization
- ā Vendor lock-in
- ā Pricing scales with users
npm install @clerk/nextjs
Option 2: NextAuth.js (Flexible)
Best for: Custom requirements, full control
Pros:
- ā Open source, self-hosted
- ā Supports any OAuth provider
- ā Database or JWT sessions
- ā Highly customizable
Cons:
- ā More setup required
- ā Handle UI yourself
- ā Security is your responsibility
npm install next-auth
Option 3: Supabase Auth (Integrated)
Best for: Using Supabase for database
Pros:
- ā Integrated with Supabase DB
- ā Row Level Security (RLS) automatically enforced
- ā Real-time session updates
- ā Magic links built-in
Cons:
- ā Tied to Supabase ecosystem
- ā Less OAuth provider support
npm install @supabase/supabase-js
Option 4: Custom Auth (Advanced)
Best for: Specific security requirements, compliance
Stack:
- bcrypt for password hashing
- jsonwebtoken for JWTs
- Prisma for session storage
- Resend for email verification
Only choose this if:
- You have security expertise
- Compliance requires specific implementation
- Other options don't meet requirements
Full Implementation Prompt
Copy this prompt to use with Claude Code:
I need to implement a complete authentication system for my app. Before we start, help me choose the right approach.
First, let me understand my requirements by asking:
- What's my current tech stack? (Framework, database, hosting)
- Do I have any specific security requirements? (HIPAA, SOC2, etc.)
- How many users do I expect? (affects auth provider choice)
- What sign-in methods do I need? (email/password, OAuth, magic links?)
- Do I need role-based access control (admin, user, etc.)?
Then let's decide on the auth strategy:
- For MVPs/startups: I recommend Clerk (fastest, handles everything)
- For custom needs: NextAuth.js (flexible, open source)
- If using Supabase: Supabase Auth (integrated, RLS support)
- For compliance: Custom implementation (full control)
After we choose, let's discuss these security considerations:
- Password hashing algorithm and salt rounds
- Session storage (JWT vs database sessions)
- Token expiration and refresh strategy
- Rate limiting for auth endpoints
- Email verification flow
- Password reset security
- OAuth callback validation
- CSRF protection
Then we'll implement in phases: Phase 1: Email/password auth with secure password hashing Phase 2: OAuth integration (Google, GitHub) Phase 3: Magic link authentication Phase 4: Session management and security hardening
Sound good? Let's start by reviewing your current setup and choosing the right auth provider.
Related Feature Specs
- Shopping Cart - Cart migration on authentication
- Admin Dashboard - Role-based access control
- Email System - Verification and password reset emails
Success Criteria
You've successfully implemented this when:
ā Users can register with email/password ā Passwords are hashed securely (bcrypt/argon2) ā Email verification works ā OAuth providers (Google, GitHub) work ā Magic link authentication works ā Password reset flow is secure ā Sessions persist across page refreshes ā Sessions expire appropriately ā Rate limiting prevents brute force attacks ā All security best practices followed
Common Security Mistakes to Avoid
ā Storing passwords in plain text or with weak hashing ā No rate limiting on auth endpoints ā Revealing if email exists during login ā Not expiring password reset tokens ā Using HTTP instead of HTTPS ā Not validating OAuth state parameter ā Not implementing CSRF protection ā Overly long session expiration (security risk)
Implementation Checklist
Setup & Configuration:
- Choose auth provider (Clerk, NextAuth, Supabase, Custom)
- Install dependencies and configure
- Set up environment variables (secrets, keys)
- Create user database schema
Email/Password Auth:
- Registration form with validation
- Password hashing (bcrypt with 12+ rounds)
- Email verification flow
- Login form with error handling
- Password strength requirements
OAuth Integration:
- Register OAuth apps (Google, GitHub)
- Configure OAuth callbacks
- Handle account linking
- Sync profile data on sign-in
Magic Links:
- Magic link email template
- Token generation with expiration
- One-time use validation
- Success/error handling
Session Management:
- JWT or database sessions
- Session expiration logic
- Refresh token rotation
- Device tracking
Security:
- Rate limiting on auth endpoints
- CSRF protection
- httpOnly, secure, sameSite cookies
- Account enumeration prevention
- Suspicious activity detection
Password Reset:
- Reset request form
- Reset email with token
- Token expiration (1 hour)
- New password form with validation
- Invalidate all sessions on reset
Testing:
- Test all sign-in methods
- Test session persistence
- Test password reset flow
- Test OAuth callbacks
- Test rate limiting
- Security audit (OWASP checklist)
Last Updated: 2025-12-04 Difficulty: Intermediate Estimated Time: 5-7 hours Prerequisites: Database schema design, security basics, email sending
Need help? Book a consultation for security audit and implementation guidance.