Implementing Authentication

Learn how to implement secure authentication systems with AgencyOS - from basic JWT authentication to OAuth2, 2FA, and passwordless login.

Overview

Goal: Implement secure, production-ready authentication Time: 20-40 minutes (vs 4-8 hours manually) Agents Used: planner, researcher, tester, code-reviewer Commands: /plan, /code, /test, /docs

Prerequisites

  • Existing API or web application
  • Database configured (PostgreSQL, MongoDB, etc.)
  • Email service for verification (optional)
  • OAuth provider accounts (optional: Google, GitHub, etc.)

Authentication Methods

MethodUse CaseSecurityComplexityTime
JWTAPI authenticationHighLow15-20 min
Session-basedTraditional web appsHighMedium20-25 min
OAuth2Social loginVery HighMedium25-35 min
PasswordlessMagic links, OTPHighMedium20-30 min
2FAAdditional securityVery HighMedium15-20 min
BiometricMobile appsVery HighHigh30-40 min

Step-by-Step Workflow

Step 1: Plan Authentication Strategy

Choose authentication method and plan implementation:

/plan [implement JWT authentication with email/password and password reset]

Generated plan:

# JWT Authentication Implementation Plan

## Components

### 1. User Model
- id (UUID)
- email (unique, indexed)
- password (hashed with bcrypt)
- emailVerified (boolean)
- resetToken (nullable)
- resetTokenExpiry (nullable)
- createdAt, updatedAt

### 2. Endpoints
- POST /api/auth/register - User registration
- POST /api/auth/login - User login
- POST /api/auth/logout - User logout
- GET /api/auth/me - Get current user
- POST /api/auth/verify-email - Email verification
- POST /api/auth/forgot-password - Request password reset
- POST /api/auth/reset-password - Reset password
- POST /api/auth/refresh-token - Refresh JWT token

### 3. Middleware
- authenticateJWT - Verify JWT token
- requireAuth - Protect routes
- checkEmailVerified - Require verified email

### 4. Security Features
- Password hashing (bcrypt, 12 rounds)
- JWT token (access + refresh)
- Token expiry (15 min access, 7 day refresh)
- Rate limiting on auth endpoints
- Email verification
- Password strength validation
- Account lockout after failed attempts

### 5. Testing
- Unit tests for auth service
- Integration tests for endpoints
- Security tests (brute force, token theft)
- E2E authentication flows

Step 2: Implement Basic JWT Authentication

/cook [implement JWT authentication with registration and login]

Implementation:

[1/6] Setting up user model...
  āœ“ Created User schema/model
  āœ“ Added password hashing hooks
  āœ“ Created database migration

[2/6] Implementing JWT service...
  āœ“ Token generation (access + refresh)
  āœ“ Token verification
  āœ“ Token refresh logic
  āœ“ Secure token storage

[3/6] Creating auth endpoints...
  āœ“ POST /api/auth/register
  āœ“ POST /api/auth/login
  āœ“ POST /api/auth/logout
  āœ“ GET /api/auth/me
  āœ“ POST /api/auth/refresh-token

[4/6] Adding middleware...
  āœ“ JWT authentication middleware
  āœ“ Route protection
  āœ“ Error handling

[5/6] Implementing validation...
  āœ“ Email format validation
  āœ“ Password strength (min 8 chars, uppercase, number, symbol)
  āœ“ Input sanitization

[6/6] Testing...
  āœ“ 32 tests generated
  āœ“ All tests pass
  āœ“ Coverage: 93%

āœ… JWT authentication implemented

Files created:
- src/models/User.js
- src/services/auth.service.js
- src/middleware/auth.middleware.js
- src/routes/auth.routes.js
- src/utils/jwt.js
- tests/auth/auth.test.js

Step 3: Add Email Verification

/cook [add email verification to registration process]

Implementation:

[1/4] Email verification setup...
  āœ“ Add verificationToken to User model
  āœ“ Generate verification tokens
  āœ“ Create verification endpoint

[2/4] Email service integration...
  āœ“ Email template for verification
  āœ“ Send verification email on registration
  āœ“ Resend verification email endpoint

[3/4] Middleware...
  āœ“ requireEmailVerified middleware
  āœ“ Apply to protected routes

[4/4] Testing...
  āœ“ Verification flow tests (8 tests)
  āœ“ Email sending mocked

āœ… Email verification added

Usage:
1. User registers → receives verification email
2. User clicks link → account verified
3. Only verified users access protected routes

Step 4: Implement Password Reset

/cook [implement password reset with email verification]

Implementation:

[1/5] Database changes...
  āœ“ Add resetToken field
  āœ“ Add resetTokenExpiry field
  āœ“ Migration created

[2/5] Reset flow endpoints...
  āœ“ POST /api/auth/forgot-password
  āœ“ POST /api/auth/reset-password
  āœ“ Token validation logic

[3/5] Email templates...
  āœ“ Password reset email
  āœ“ Password changed confirmation

[4/5] Security measures...
  āœ“ Token expiry (15 minutes)
  āœ“ Single-use tokens
  āœ“ Rate limiting (5 requests/hour)

[5/5] Testing...
  āœ“ Reset flow tests (12 tests)
  āœ“ Security tests (token expiry, reuse)

āœ… Password reset implemented

Step 5: Add OAuth2 (Social Login)

/cook [add OAuth2 login with Google and GitHub]

Implementation:

[1/6] OAuth setup...
  āœ“ Installed passport.js
  āœ“ Configured Google strategy
  āœ“ Configured GitHub strategy

[2/6] OAuth endpoints...
  āœ“ GET /api/auth/google
  āœ“ GET /api/auth/google/callback
  āœ“ GET /api/auth/github
  āœ“ GET /api/auth/github/callback

[3/6] User model updates...
  āœ“ Add oauthProvider field
  āœ“ Add oauthId field
  āœ“ Link OAuth accounts to existing users

[4/6] Account linking...
  āœ“ Link OAuth to email if exists
  āœ“ Create new user if doesn't exist
  āœ“ Merge accounts logic

[5/6] Frontend integration...
  āœ“ OAuth buttons
  āœ“ Redirect handling
  āœ“ Token extraction

[6/6] Testing...
  āœ“ OAuth flow tests (16 tests)
  āœ“ Account linking tests

āœ… OAuth2 implemented

Configuration needed (.env):
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-secret
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-secret

Step 6: Add Two-Factor Authentication (2FA)

/cook [implement TOTP-based 2FA with QR code setup]

Implementation:

[1/5] 2FA setup...
  āœ“ Installed speakeasy (TOTP library)
  āœ“ Installed qrcode (QR generation)
  āœ“ Add twoFactorSecret to User model
  āœ“ Add twoFactorEnabled field

[2/5] 2FA endpoints...
  āœ“ POST /api/auth/2fa/setup - Generate QR code
  āœ“ POST /api/auth/2fa/verify - Verify and enable
  āœ“ POST /api/auth/2fa/disable - Disable 2FA
  āœ“ POST /api/auth/login/2fa - Login with 2FA code

[3/5] Modified login flow...
  āœ“ Check if 2FA enabled
  āœ“ Require 2FA code
  āœ“ Validate TOTP token

[4/5] Backup codes...
  āœ“ Generate 10 backup codes
  āœ“ Store hashed backup codes
  āœ“ Use backup code endpoint

[5/5] Testing...
  āœ“ 2FA flow tests (14 tests)
  āœ“ Backup code tests

āœ… 2FA implemented

Flow:
1. User enables 2FA → scans QR code
2. User enters 6-digit code → 2FA activated
3. Future logins require 2FA code
4. Backup codes for emergencies

Step 7: Add Passwordless Authentication

/cook [implement passwordless login with magic links]

Implementation:

[1/4] Magic link setup...
  āœ“ Generate secure login tokens
  āœ“ Store tokens with expiry (10 min)
  āœ“ Email template for magic link

[2/4] Endpoints...
  āœ“ POST /api/auth/magic-link/request
  āœ“ GET /api/auth/magic-link/verify
  āœ“ Token validation and cleanup

[3/4] Security...
  āœ“ Single-use tokens
  āœ“ Short expiry (10 minutes)
  āœ“ Rate limiting

[4/4] Testing...
  āœ“ Magic link flow tests (10 tests)

āœ… Passwordless authentication added

Usage:
1. User enters email
2. Receives magic link email
3. Clicks link → automatically logged in

Step 8: Add Security Features

Account Lockout

/cook [add account lockout after 5 failed login attempts]

Session Management

/cook [implement session management with active session tracking]

IP Whitelisting

/cook [add IP whitelisting option for high-security accounts]

Step 9: Testing Authentication

/test

Test results:

āœ“ Unit Tests (48 tests)
  āœ“ Password hashing (8 tests)
  āœ“ JWT generation/verification (12 tests)
  āœ“ Token refresh (6 tests)
  āœ“ 2FA TOTP (10 tests)
  āœ“ Magic link generation (6 tests)
  āœ“ OAuth account linking (6 tests)

āœ“ Integration Tests (56 tests)
  āœ“ Registration (10 tests)
  āœ“ Login (12 tests)
  āœ“ Password reset (12 tests)
  āœ“ OAuth flows (14 tests)
  āœ“ 2FA flows (8 tests)

āœ“ Security Tests (24 tests)
  āœ“ Brute force protection (6 tests)
  āœ“ Token theft scenarios (8 tests)
  āœ“ SQL injection attempts (4 tests)
  āœ“ XSS attempts (6 tests)

Test Suites: 3 passed, 3 total
Tests:       128 passed, 128 total
Coverage:    94.7%

āœ… All tests passed

Step 10: Security Review

/review

Security checklist:

āœ“ Passwords hashed with bcrypt (12 rounds)
āœ“ JWT tokens properly signed
āœ“ Refresh tokens securely stored
āœ“ Rate limiting on auth endpoints
āœ“ SQL injection protection
āœ“ XSS protection
āœ“ CSRF protection
āœ“ Secure password requirements
āœ“ Email verification implemented
āœ“ Account lockout after failed attempts
āœ“ 2FA option available
āœ“ Session timeout configured
āœ“ Secure token storage
āœ“ HTTPS enforcement
āœ“ Audit logging enabled

Security Score: 9.4/10 (Excellent)

Step 11: Documentation

/docs:update

Generated documentation:

āœ“ Authentication guide
āœ“ API endpoint documentation
āœ“ Security best practices
āœ“ OAuth setup guide
āœ“ 2FA setup guide
āœ“ Testing guide
āœ“ Troubleshooting guide

Complete Example: E-Commerce Authentication

Requirements

Implement authentication for e-commerce site with:
- User registration/login
- Email verification
- Password reset
- Social login (Google, Facebook)
- Guest checkout
- Remember me option
- Account deletion
- GDPR compliance

Implementation

# Plan authentication
/plan [design authentication system for e-commerce with all requirements]

# Implement base auth
/cook [implement JWT authentication with email verification]

# Add OAuth
/cook [add Google and Facebook OAuth login]

# Guest checkout
/cook [implement guest checkout with optional account creation]

# Remember me
/cook [add remember me functionality with long-lived tokens]

# Account management
/cook [implement account deletion with data export (GDPR)]

# Test everything
/test

# Document
/docs:update

Time Comparison

Manual implementation: 6-10 hours

  • JWT setup: 1-2 hours
  • Email verification: 1 hour
  • Password reset: 1 hour
  • OAuth setup: 2-3 hours
  • Testing: 1-2 hours
  • Security review: 1-2 hours

With AgencyOS: 38 minutes

  • Planning: 5 minutes
  • JWT + email: 10 minutes
  • Password reset: 5 minutes
  • OAuth: 12 minutes
  • Testing: 6 minutes

Time saved: 5.5-9.5 hours (88% faster)

Authentication Patterns

Pattern 1: API-First Authentication

/cook [implement JWT authentication optimized for mobile apps]

Pattern 2: SSO (Single Sign-On)

/cook [implement SSO with SAML for enterprise integration]

Pattern 3: Multi-Tenant Authentication

/cook [implement multi-tenant authentication with organization isolation]

Pattern 4: Role-Based Access Control (RBAC)

/cook [add role-based permissions with admin, user, and guest roles]

Best Practices

1. Secure Password Storage

āœ… Good:
- bcrypt with 12+ rounds
- Async password hashing
- Never store plain text

āŒ Bad:
- MD5/SHA1 hashing
- No salt
- Plain text passwords

2. JWT Token Security

āœ… Good:
- Short access token expiry (15 min)
- Refresh token rotation
- Secure token storage (httpOnly cookies)
- Token blacklisting on logout

āŒ Bad:
- Long-lived tokens
- Tokens in localStorage
- No token refresh
- No logout mechanism

3. Input Validation

/cook [add comprehensive input validation to all auth endpoints]

4. Rate Limiting

Auth endpoints rate limits:
- Login: 5 attempts per 15 minutes
- Registration: 3 per hour
- Password reset: 3 per hour
- Email verification: 5 per hour

5. Audit Logging

/cook [add audit logging for all authentication events]

Troubleshooting

Issue: Tokens Expiring Too Fast

Solution:

/cook [increase JWT access token expiry to 30 minutes]

Issue: OAuth Callback Failing

Solution:

/fix:fast [OAuth callback returning 400 error]

Issue: Password Reset Not Working

Solution:

/fix:fast [password reset emails not being sent]

Issue: 2FA QR Code Not Displaying

Solution:

/fix:ui [2FA QR code not rendering in mobile view]

Security Checklist

Before production deployment:

āœ“ All passwords hashed with bcrypt
āœ“ JWT tokens use strong secret
āœ“ Refresh token rotation enabled
āœ“ Rate limiting configured
āœ“ HTTPS enforced
āœ“ CORS properly configured
āœ“ Input validation on all endpoints
āœ“ SQL injection protection
āœ“ XSS protection
āœ“ CSRF protection
āœ“ Email verification working
āœ“ Password reset tested
āœ“ OAuth redirect URIs whitelisted
āœ“ 2FA tested with multiple apps
āœ“ Account lockout working
āœ“ Audit logging enabled
āœ“ Error messages don't leak info
āœ“ Session timeout configured
āœ“ Secure cookies (httpOnly, secure)
āœ“ Token blacklist on logout

Next Steps

Integration Guides

Further Reading


Key Takeaway: AgencyOS enables rapid implementation of secure, production-ready authentication with industry best practices built-in - from basic JWT to OAuth2 and 2FA in under an hour.