Lego Block: Authentication & Authorization

Enterprise Auth System

Complete authentication and authorization solution with multiple auth methods, role-based access control, multi-factor authentication, session management, and comprehensive security features.

5+
Auth Methods
RBAC
Fine-grained Control
MFA
Multi-factor Auth
SSO
Enterprise Single Sign-On
Password Auth
OAuth 2.0
SSO/SAML
MFA/2FA
RBAC
Audit Logs

Scope & Overview

A production-ready authentication and authorization system with enterprise-grade security features, multiple authentication methods, granular access control, and comprehensive audit capabilities.

Must-Have Features

  • User registration and login with email/password
  • Password hashing with bcrypt (cost factor 12+)
  • OAuth 2.0 integration (Google, GitHub, Microsoft)
  • Role-based access control (RBAC) with permissions
  • Session management with secure tokens
  • Multi-factor authentication (TOTP, SMS)
  • Password reset and email verification flows
  • Account lockout after failed login attempts
  • Audit logging for all auth events
  • JWT token-based API authentication

Nice-to-Have Features

  • SAML 2.0 support for enterprise SSO
  • Social login (Facebook, Twitter, LinkedIn)
  • WebAuthn/FIDO2 for passwordless auth
  • Refresh token rotation strategy
  • Device management and trusted devices
  • IP whitelisting and geofencing
  • Session timeout and idle detection
  • Security question recovery
  • Admin panel for user management
  • Compliance reporting (SOC2, GDPR)

System Architecture

A secure, scalable four-tier architecture built with Next.js, Node.js, and PostgreSQL, featuring JWT-based authentication, OAuth integration, and comprehensive security controls.

Frontend Layer

React / Next.js

Auth forms, protected routes, role guards, MFA enrollment UI

Backend Layer

Node.js / Next.js API Routes

Auth endpoints, token validation, OAuth providers, session management

Security Layer

bcrypt, JWT, TOTP

Password hashing, token signing, MFA verification, rate limiting

Data Layer

PostgreSQL / MySQL

Users, sessions, roles, permissions, audit logs, OAuth tokens

Integration Points

OAuth Providers
  • • Google OAuth 2.0
  • • GitHub OAuth
  • • Microsoft Azure AD
  • • Custom OIDC providers
MFA Methods
  • • TOTP (Google Authenticator)
  • • SMS verification
  • • Email verification codes
  • • Backup recovery codes
Security Features
  • • Rate limiting per IP
  • • Account lockout policy
  • • Session hijacking detection
  • • CSRF protection

Authentication Methods

Support multiple authentication methods to meet diverse user needs and security requirements, from traditional credentials to modern passwordless and social login options.

Email & Password

Classic registration and login with secure password hashing

  • bcrypt hashing (cost factor 12+)
  • Password strength validation
  • Email verification required
  • Forgot password flow
  • Rate limiting on attempts

OAuth 2.0

Social login with Google, GitHub, and other providers

  • Authorization code flow
  • Automatic account linking
  • Profile data sync
  • Refresh token handling
  • Scope-based permissions

Enterprise SSO

SAML 2.0 and OIDC for enterprise identity providers

  • SAML 2.0 IdP integration
  • OpenID Connect support
  • Just-in-time provisioning
  • Attribute mapping
  • Group synchronization

Multi-Factor Auth

Additional security layer with TOTP, SMS, or email codes

  • TOTP app integration
  • SMS verification codes
  • Email OTP delivery
  • Backup recovery codes
  • Device trust management

API Authentication

JWT-based authentication for API access and integrations

  • JWT token signing (RS256)
  • Access + refresh tokens
  • Token rotation strategy
  • API key management
  • Scoped permissions

Database Schema

A comprehensive PostgreSQL schema supporting users, OAuth accounts, sessions, RBAC, MFA settings, and complete audit logging with proper indexes for optimal performance.

users

Core user identity and credentials

id (UUID, PK)
email (unique, indexed)
password_hash (bcrypt)
email_verified (boolean)
is_active (boolean)
failed_login_attempts (int)
locked_until (timestamp, nullable)
created_at, updated_at

oauth_accounts

Linked OAuth provider accounts

id (UUID, PK)
user_id (FK → users)
provider (google, github, etc.)
provider_user_id (indexed)
access_token (encrypted)
refresh_token (encrypted)
expires_at (timestamp)
created_at, updated_at

sessions

Active user sessions and tokens

id (UUID, PK)
user_id (FK → users)
token (unique, indexed)
refresh_token (unique)
ip_address (varchar)
user_agent (text)
expires_at (timestamp, indexed)
created_at, last_accessed_at

roles

User roles for RBAC

id (UUID, PK)
name (unique, e.g., admin, user)
description (text)
created_at

permissions

Fine-grained permissions

id (UUID, PK)
name (unique, e.g., users:read)
resource (varchar)
action (varchar)
description (text)
created_at

role_permissions

Many-to-many role-permission mapping

role_id (FK → roles)
permission_id (FK → permissions)
granted_at

user_roles

Many-to-many user-role mapping

user_id (FK → users)
role_id (FK → roles)
assigned_at
assigned_by (FK → users)

mfa_settings

Multi-factor authentication settings

id (UUID, PK)
user_id (FK → users, unique)
mfa_enabled (boolean)
totp_secret (encrypted, nullable)
backup_codes (encrypted JSON)
phone_number (encrypted, nullable)
created_at, updated_at

audit_logs

Complete audit trail of auth events

id (UUID, PK)
user_id (FK → users, nullable)
event_type (enum: login, logout, mfa, etc.)
ip_address (varchar)
user_agent (text)
success (boolean)
metadata (JSONB)
created_at (indexed)

Key Indexes & Constraints

Performance Indexes
  • • users(email) - unique index
  • • sessions(token) - unique index
  • • sessions(expires_at) - for cleanup
  • • audit_logs(created_at) - time-series
  • • oauth_accounts(provider_user_id)
Data Integrity
  • • Foreign keys with ON DELETE CASCADE
  • • Check constraints on enums
  • • Unique constraints on tokens
  • • NOT NULL on critical fields
  • • Encrypted storage for secrets

Role-Based Access Control (RBAC)

Implement fine-grained authorization with roles, permissions, and resource-level access control for enterprise-grade security and flexibility.

Roles

Roles group related permissions and can be assigned to users. Support for role hierarchies and inheritance.

Example Roles
adminFull system access
managerTeam management
userStandard access
guestRead-only access
• Users can have multiple roles
• Roles are composable and reusable
• Support for custom role creation

Permissions

Fine-grained permissions define specific actions on resources using a resource:action pattern.

Permission Format
users:read
users:write
users:delete
reports:generate
settings:manage
billing:view
• Wildcard support (users:*)
• Resource-level scoping
• Dynamic permission evaluation

Authorization Flow

1
Request
User attempts action on resource
2
Authenticate
Verify user identity from token
3
Check Permissions
Query user roles and permissions
4
Allow/Deny
Grant or reject access
Middleware Guards
  • • RequireAuth
  • • RequireRole(['admin'])
  • • RequirePermission('users:write')
  • • RequireOwnership
React Components
  • <ProtectedRoute />
  • <RequireRole role="admin" />
  • <Can do="edit" on="users" />
  • <usePermissions />
API Helpers
  • hasPermission()
  • hasRole()
  • canAccess()
  • checkOwnership()

Security Features

Enterprise-grade security with multiple layers of protection including password policies, brute force prevention, session security, and comprehensive audit logging.

Password Security

  • bcrypt hashing with cost factor 12+
  • Minimum length and complexity requirements
  • Password strength meter
  • Breach detection via HaveIBeenPwned API
  • Password history to prevent reuse
  • Forced password rotation policies

Brute Force Protection

  • Rate limiting per IP address
  • Account lockout after N failed attempts
  • Progressive delay on failed logins
  • CAPTCHA after repeated failures
  • Automatic unlock after time period
  • Admin notification on suspicious activity

Session Security

  • Secure, HttpOnly, SameSite cookies
  • CSRF token validation
  • Session hijacking detection via fingerprint
  • Automatic session expiration
  • Concurrent session limits
  • Device tracking and management

Audit & Monitoring

  • Complete audit log of all auth events
  • Login history with IP and device
  • Failed login attempt tracking
  • Permission change logging
  • Anomaly detection alerts
  • Compliance reporting (GDPR, SOC2)

Additional Security Measures

Network Security
  • • IP whitelisting for admin
  • • Geofencing restrictions
  • • TLS 1.3 encryption
  • • DDoS protection
Data Protection
  • • Encrypted sensitive data at rest
  • • Token encryption in database
  • • PII data masking in logs
  • • Secure key management
Compliance
  • • GDPR data export/deletion
  • • SOC 2 audit trails
  • • HIPAA compliance ready
  • • Regular security audits

Session Management

Secure session handling with JWT tokens, refresh token rotation, device tracking, and automatic expiration for optimal security and user experience.

Token Strategy

Access Token (JWT)
  • Short-lived (15 minutes)
  • Contains user ID, roles, permissions
  • Signed with RS256 algorithm
  • Stored in memory (not localStorage)
Refresh Token
  • Long-lived (7 days)
  • HttpOnly, Secure cookie
  • Rotation on use (new token issued)
  • Revokable from database

Device Management

Track and manage active sessions across multiple devices with the ability to view and revoke access.

Session Information
Device TypeDesktop, Mobile, Tablet
BrowserChrome, Safari, Firefox
IP Address192.168.1.1
LocationCity, Country
Last Active2 minutes ago
Session Actions
  • • View all active sessions
  • • Revoke individual sessions
  • • Logout from all devices
  • • Mark devices as trusted

Session Lifecycle

1
Login
User authenticates successfully
2
Issue Tokens
Generate access + refresh tokens
3
Verify Requests
Validate access token on each request
4
Refresh
Use refresh token to get new access token
5
Expire/Logout
Session ends or user logs out
Automatic Expiration
  • • Idle timeout (30 min)
  • • Absolute timeout (12 hours)
  • • Refresh token expiry (7 days)
  • • Background cleanup job
Security Checks
  • • User agent fingerprinting
  • • IP address validation
  • • Concurrent session limits
  • • Token reuse detection
User Experience
  • • Silent refresh in background
  • • Remember me option
  • • Graceful session expiry
  • • Auto-save before logout

Multi-Factor Authentication

Add an extra layer of security with multiple MFA options including authenticator apps, email codes, and backup recovery codes for account protection.

Authenticator App (TOTP)

Time-based one-time passwords using Google Authenticator, Authy, or similar apps

Setup Flow
  1. 1.User enables MFA in settings
  2. 2.Server generates TOTP secret
  3. 3.Display QR code for scanning
  4. 4.User enters verification code
  5. 5.Generate backup codes
Verification Flow
  1. 1.User enters 6-digit code
  2. 2.Server validates TOTP
  3. 3.Compare within time window (30s)
  4. 4.Allow access if valid

Email Verification Code

One-time codes sent to user's registered email address

Setup Flow
  1. 1.User opts for email MFA
  2. 2.Verify email ownership
  3. 3.Store preference in database
  4. 4.Ready for login challenges
Verification Flow
  1. 1.Generate 6-digit code
  2. 2.Send to registered email
  3. 3.User enters code (5 min TTL)
  4. 4.Validate and grant access

Backup Recovery Codes

Single-use codes for account recovery when primary MFA is unavailable

Setup Flow
  1. 1.Generate 10 random codes
  2. 2.Display to user once
  3. 3.User saves securely
  4. 4.Mark as unused in database
Verification Flow
  1. 1.User enters recovery code
  2. 2.Check if unused
  3. 3.Mark code as used
  4. 4.Allow one-time access

MFA Best Practices

Implementation
  • • Optional but strongly encouraged
  • • Required for admin/sensitive roles
  • • Support multiple backup methods
  • • Remember trusted devices (30 days)
  • • Rate limit verification attempts
User Experience
  • • Clear enrollment instructions
  • • QR code and manual entry option
  • • Show recovery codes prominently
  • • Easy method switching
  • • Admin bypass for emergencies
Security
  • • Encrypt TOTP secrets at rest
  • • Single-use backup codes
  • • Time window validation (±1 step)
  • • Log all MFA events
  • • Alert on MFA changes

API Endpoints

RESTful API for authentication, registration, OAuth, MFA, session management, and user profile operations with JWT-based authorization.

POST/api/auth/register

Register new user with email and password

Request: { email, password, name }
Response: { user, accessToken, refreshToken }
POST/api/auth/login

Authenticate user with credentials

Request: { email, password }
Response: { user, accessToken, refreshToken, requiresMfa }
POST/api/auth/verify-mfa

Verify MFA code after login

Request: { code, sessionId }
Response: { accessToken, refreshToken }
POST/api/auth/refresh

Get new access token using refresh token

Request: { refreshToken }
Response: { accessToken, refreshToken }
POST/api/auth/logout

Invalidate session and tokens

Request: { refreshToken }
Response: { success: true }
POST/api/auth/forgot-password

Send password reset email

Request: { email }
Response: { message: 'Reset link sent' }
POST/api/auth/reset-password

Reset password with token

Request: { token, newPassword }
Response: { success: true }
POST/api/auth/verify-email

Verify email address with token

Request: { token }
Response: { user, verified: true }
GET/api/auth/oauth/:provider

Initiate OAuth flow (Google, GitHub, etc.)

Request: query: { redirectUrl }
Response: Redirect to provider
GET/api/auth/oauth/callback

Handle OAuth callback

Request: query: { code, state }
Response: { user, accessToken, refreshToken }
POST/api/auth/mfa/setup

Setup MFA (TOTP)

Request: Auth header
Response: { secret, qrCode, backupCodes }
POST/api/auth/mfa/enable

Enable MFA after verification

Request: { code }
Response: { enabled: true }
GET/api/users/me

Get current user profile

Request: Auth header
Response: { user, roles, permissions }
GET/api/users/sessions

List active sessions

Request: Auth header
Response: { sessions: [...] }
DELETE/api/users/sessions/:id

Revoke specific session

Request: Auth header
Response: { success: true }

Authentication Header

Protected Endpoints
Authorization: Bearer <access_token>

Include JWT access token in Authorization header for protected routes.

Error Responses
  • • 401 Unauthorized - Invalid/expired token
  • • 403 Forbidden - Insufficient permissions
  • • 429 Too Many Requests - Rate limited
  • • 422 Validation Error - Invalid input

User Interface

Modern, responsive React UI components for all authentication flows including login, registration, password reset, MFA setup, and security settings.

Login Page

User login with email/password and social OAuth options

  • Email and password inputs
  • Remember me checkbox
  • Forgot password link
  • Social login buttons
  • MFA code input (if enabled)

Registration Page

New user signup with validation and email verification

  • Name, email, password fields
  • Password strength meter
  • Terms acceptance checkbox
  • Email verification flow
  • Success confirmation

Security Settings

User security preferences and MFA configuration

  • Change password form
  • Enable/disable MFA toggle
  • MFA setup wizard
  • Backup codes display
  • Active sessions list

Device Management

View and manage active sessions across devices

  • List of active sessions
  • Device type and location
  • Last accessed timestamp
  • Revoke session button
  • Logout all devices

Additional UI Components

Authentication Forms
  • • Forgot password form
  • • Reset password form
  • • Email verification page
  • • MFA verification modal
  • • OAuth consent screens
Protected Routes
  • • Route guards for auth
  • • Role-based navigation
  • • Permission-based UI
  • • Redirect after login
  • • Loading states
Admin Dashboard
  • • User management table
  • • Role assignment interface
  • • Permission editor
  • • Audit log viewer
  • • Security alerts panel

Why Choose This Auth System?

A complete, production-ready authentication and authorization solution that combines security, flexibility, and ease of use for modern applications.

Enterprise-Grade Security

Industry-standard encryption, password policies, and security controls to protect user data.

Multiple Auth Methods

Support for email/password, OAuth, SSO, and MFA to meet diverse user needs.

Fine-Grained Access Control

RBAC with permissions for precise control over who can access what resources.

Fast & Scalable

JWT-based authentication with optimized database queries and caching for high performance.

Easy Integration

RESTful API with clear documentation and React components for quick implementation.

Production Ready

Comprehensive error handling, logging, and monitoring for reliable production deployment.

Definition of Done

Complete authentication system with registration, login, and password reset
OAuth 2.0 integration with Google, GitHub, and Microsoft
Enterprise SSO with SAML 2.0 support
Multi-factor authentication with TOTP, SMS, and email
Role-based access control with fine-grained permissions
Session management with JWT tokens and refresh rotation
Device tracking and trusted device management
Password security with bcrypt hashing and strength validation
Brute force protection with rate limiting and account lockout
Comprehensive audit logging for all auth events
Security features including CSRF protection and session hijacking detection
React UI components for all auth flows
Admin dashboard for user and role management
PostgreSQL database schema with proper indexes
RESTful API with clear documentation

Build Your Next Product With AI Expertise

Experience the future of software development. Let our GenAI platform accelerate your next project.

Schedule a Free AI Blueprint Session