Back to Documentation
Authentication
Implement JWT auth, RBAC, MFA, and OAuth providers
Quick Setup
Add authentication to your project with a single command
servcraft add authservcraft add usersservcraft add mfaservcraft add oauthInstall Authentication
# Complete authentication setup servcraft add auth servcraft add users servcraft add mfa servcraft add oauth # Or all at once servcraft init my-app --add-auth
Authentication Features
JWT Tokens
Access and refresh token authentication with secure token management
Role-Based Access
RBAC with roles and permissions system for fine-grained access control
User Management
Complete user CRUD with profile management and activity tracking
MFA Support
Two-factor authentication with TOTP apps and backup codes
OAuth Providers
Social login with Google, GitHub, Facebook, Twitter, and Apple
Password Security
Secure password hashing with bcrypt and password policies
Configuration
src/modules/auth/config.ts
1// src/modules/auth/config.ts2export const authConfig = {3// JWT Configuration4jwt: {5accessTokenSecret: process.env.JWT_ACCESS_SECRET!,6refreshTokenSecret: process.env.JWT_REFRESH_SECRET!,7accessTokenExpiry: "15m", // 15 minutes8refreshTokenExpiry: "7d", // 7 days9},1011// Password Configuration12password: {13bcryptRounds: 12,14minLength: 8,15requireUppercase: true,16requireLowercase: true,17requireNumber: true,18requireSpecialChar: true,19},2021// MFA Configuration22mfa: {23issuer: "ServCraft",24window: 1, // Allow 1 step drift25},2627// Rate Limiting28rateLimit: {29login: { windowMs: 15 * 60 * 1000, max: 5 }, // 5 attempts per 15 min30register: { windowMs: 60 * 60 * 1000, max: 3 }, // 3 per hour31},32};
Basic Usage
Auth Controller Example
1// src/modules/auth/auth.service.ts2import { authService } from './service';3import { jwtService } from './jwt';45class AuthController {6// Register new user7async register(req, res) {8const { email, password, name } = req.body;910// Check if user exists11const existingUser = await userService.findByEmail(email);12if (existingUser) {13throw new HttpError(400, 'Email already registered');14}1516// Create user with hashed password17const user = await userService.create({18email,19password, // Will be hashed automatically20name,21role: 'USER',22});2324// Generate tokens25const tokens = await authService.generateTokens(user);2627res.status(201).json({28user: user.toResponse(),29...tokens,30});31}3233// Login34async login(req, res) {35const { email, password } = req.body;3637const user = await userService.findByEmail(email);38if (!user) {39throw new HttpError(401, 'Invalid credentials');40}4142// Verify password43const isValid = await bcrypt.compare(password, user.password);44if (!isValid) {45throw new HttpError(401, 'Invalid credentials');46}4748// Generate tokens49const tokens = await authService.generateTokens(user);5051res.json({52user: user.toResponse(),53...tokens,54});55}5657// Refresh token58async refresh(req, res) {59const { refreshToken } = req.body;6061const payload = jwtService.verifyRefresh(refreshToken);62const user = await userService.findById(payload.userId);6364if (!user || user.refreshToken !== refreshToken) {65throw new HttpError(401, 'Invalid refresh token');66}6768const tokens = await authService.generateTokens(user);6970res.json(tokens);71}72}
Protecting Routes
Using Auth Middleware
1// src/middleware/auth.ts2import { authMiddleware } from '../modules/auth';34// Protect routes - requires valid JWT5app.get('/api/protected',6authMiddleware,7(req, res) => {8// req.user is available here9const user = req.user;10res.json({ message: 'Protected data', user });11}12);1314// Role-based access control15app.get('/api/admin',16authMiddleware,17authMiddleware.requireRole('ADMIN'),18(req, res) => {19res.json({ message: 'Admin data' });20}21);2223// Custom permission check24app.get('/api/dashboard',25authMiddleware,26authMiddleware.requirePermission('dashboard:read'),27(req, res) => {28res.json({ message: 'Dashboard data' });29}30);