Coherent.js API Security Guide
This guide covers the comprehensive security features built into the Coherent.js API framework and best practices for secure API development.
Table of Contents
- Built-in Security Features
- Authentication & Authorization
- Input Validation & Sanitization
- Rate Limiting & DoS Protection
- Security Headers
- CORS Configuration
- Request Size Limits
- Password Security
- Security Best Practices
- Common Vulnerabilities Prevention
Built-in Security Features
The Coherent.js API framework includes enterprise-grade security features out of the box:
- Automatic Security Headers - CORS, XSS protection, content type sniffing prevention
- Rate Limiting - IP-based request throttling with configurable windows
- Input Sanitization - XSS prevention and prototype pollution protection
- Request Size Limits - Protection against large payload attacks
- Authentication Middleware - JWT-based authentication with role support
- Input Validation - JSON Schema validation with security considerations
Authentication & Authorization
JWT Token Authentication
const { withAuth, withRole, generateToken } = require('../src/api/security');
// Generate tokens
const token = generateToken({
userId: 123,
username: 'john_doe',
role: 'user',
permissions: ['read', 'write']
}, '24h'); // Token expires in 24 hours
// Protected routes
const routes = {
api: {
profile: {
GET: {
middleware: [withAuth],
handler: async (req, res) => {
// req.user contains decoded token data
return { user: req.user };
}
}
},
admin: {
GET: {
middleware: [withAuth, withRole('admin')],
handler: async (req, res) => {
return { message: 'Admin access granted' };
}
}
}
}
};Custom Authentication
const customAuth = async (req, res) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey || !await validateApiKey(apiKey)) {
res.statusCode = 401;
throw new Error('Invalid API key');
}
req.user = await getUserByApiKey(apiKey);
};
const routes = {
api: {
data: {
GET: {
middleware: [customAuth],
handler: async (req, res) => {
return { data: 'Protected data' };
}
}
}
}
};Input Validation & Sanitization
JSON Schema Validation
const { withValidation } = require('../src/api/security');
const userSchema = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 3,
maxLength: 30,
pattern: '^[a-zA-Z0-9_]+