All Features / User Authentication System
5-7 hours
intermediate

User Authentication System

Email/password + OAuth + magic links + session management

authsecuritysaas

Paste this into Claude Code to start implementing

šŸ”§Works With

This spec is compatible with:

The implementation prompt includes guidance for these tech stacks.

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:

  1. Choose your auth provider first - Clerk (easiest), NextAuth (flexible), Supabase (integrated), or custom
  2. Never store passwords in plain text - Use bcrypt or argon2 with proper salt rounds
  3. Implement rate limiting - Prevent brute force attacks on login endpoints
  4. 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:

  1. What's my current tech stack? (Framework, database, hosting)
  2. Do I have any specific security requirements? (HIPAA, SOC2, etc.)
  3. How many users do I expect? (affects auth provider choice)
  4. What sign-in methods do I need? (email/password, OAuth, magic links?)
  5. 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

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.

Need Implementation Help?

Get expert guidance on architecture, security, and best practices.

Book a Consultation
User Authentication System | Claude Code Implementation Guide | HashBuilds