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 auth
servcraft add users
servcraft add mfa
servcraft add oauth
Install 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.ts
2export const authConfig = {
3 // JWT Configuration
4 jwt: {
5 accessTokenSecret: process.env.JWT_ACCESS_SECRET!,
6 refreshTokenSecret: process.env.JWT_REFRESH_SECRET!,
7 accessTokenExpiry: "15m", // 15 minutes
8 refreshTokenExpiry: "7d", // 7 days
9 },
10
11 // Password Configuration
12 password: {
13 bcryptRounds: 12,
14 minLength: 8,
15 requireUppercase: true,
16 requireLowercase: true,
17 requireNumber: true,
18 requireSpecialChar: true,
19 },
20
21 // MFA Configuration
22 mfa: {
23 issuer: "ServCraft",
24 window: 1, // Allow 1 step drift
25 },
26
27 // Rate Limiting
28 rateLimit: {
29 login: { windowMs: 15 * 60 * 1000, max: 5 }, // 5 attempts per 15 min
30 register: { windowMs: 60 * 60 * 1000, max: 3 }, // 3 per hour
31 },
32};

Basic Usage

Auth Controller Example
1// src/modules/auth/auth.service.ts
2import { authService } from './service';
3import { jwtService } from './jwt';
4
5class AuthController {
6 // Register new user
7 async register(req, res) {
8 const { email, password, name } = req.body;
9
10 // Check if user exists
11 const existingUser = await userService.findByEmail(email);
12 if (existingUser) {
13 throw new HttpError(400, 'Email already registered');
14 }
15
16 // Create user with hashed password
17 const user = await userService.create({
18 email,
19 password, // Will be hashed automatically
20 name,
21 role: 'USER',
22 });
23
24 // Generate tokens
25 const tokens = await authService.generateTokens(user);
26
27 res.status(201).json({
28 user: user.toResponse(),
29 ...tokens,
30 });
31 }
32
33 // Login
34 async login(req, res) {
35 const { email, password } = req.body;
36
37 const user = await userService.findByEmail(email);
38 if (!user) {
39 throw new HttpError(401, 'Invalid credentials');
40 }
41
42 // Verify password
43 const isValid = await bcrypt.compare(password, user.password);
44 if (!isValid) {
45 throw new HttpError(401, 'Invalid credentials');
46 }
47
48 // Generate tokens
49 const tokens = await authService.generateTokens(user);
50
51 res.json({
52 user: user.toResponse(),
53 ...tokens,
54 });
55 }
56
57 // Refresh token
58 async refresh(req, res) {
59 const { refreshToken } = req.body;
60
61 const payload = jwtService.verifyRefresh(refreshToken);
62 const user = await userService.findById(payload.userId);
63
64 if (!user || user.refreshToken !== refreshToken) {
65 throw new HttpError(401, 'Invalid refresh token');
66 }
67
68 const tokens = await authService.generateTokens(user);
69
70 res.json(tokens);
71 }
72}

Protecting Routes

Using Auth Middleware
1// src/middleware/auth.ts
2import { authMiddleware } from '../modules/auth';
3
4// Protect routes - requires valid JWT
5app.get('/api/protected',
6 authMiddleware,
7 (req, res) => {
8 // req.user is available here
9 const user = req.user;
10 res.json({ message: 'Protected data', user });
11 }
12);
13
14// Role-based access control
15app.get('/api/admin',
16 authMiddleware,
17 authMiddleware.requireRole('ADMIN'),
18 (req, res) => {
19 res.json({ message: 'Admin data' });
20 }
21);
22
23// Custom permission check
24app.get('/api/dashboard',
25 authMiddleware,
26 authMiddleware.requirePermission('dashboard:read'),
27 (req, res) => {
28 res.json({ message: 'Dashboard data' });
29 }
30);

Ready to Explore More?