CORS Best Practices
CORS Best Practices
// Comprehensive CORS security implementation
class SecureCORSHandler {
constructor(config) {
this.allowedOrigins = new Set(config.allowedOrigins || []);
this.allowedMethods = config.allowedMethods || ['GET', 'POST', 'PUT', 'DELETE'];
this.allowedHeaders = config.allowedHeaders || ['Content-Type', 'Authorization'];
this.exposedHeaders = config.exposedHeaders || [];
this.maxAge = config.maxAge || 86400;
this.credentials = config.credentials || false;
}
middleware() {
return (req, res, next) => {
const origin = req.headers.origin;
// Check if origin is allowed
if (this.isOriginAllowed(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
if (this.credentials) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
if (this.exposedHeaders.length > 0) {
res.setHeader('Access-Control-Expose-Headers',
this.exposedHeaders.join(', '));
}
}
// Handle preflight
if (req.method === 'OPTIONS') {
if (this.isOriginAllowed(origin)) {
res.setHeader('Access-Control-Allow-Methods',
this.allowedMethods.join(', '));
res.setHeader('Access-Control-Allow-Headers',
this.allowedHeaders.join(', '));
res.setHeader('Access-Control-Max-Age', this.maxAge);
}
res.status(204).end();
return;
}
next();
};
}
isOriginAllowed(origin) {
// Never allow null origin
if (!origin || origin === 'null') {
return false;
}
// Check against whitelist
return this.allowedOrigins.has(origin);
}
addAllowedOrigin(origin) {
// Validate origin format
try {
new URL(origin);
this.allowedOrigins.add(origin);
} catch (error) {
throw new Error(`Invalid origin format: ${origin}`);
}
}
}
// Usage
const corsHandler = new SecureCORSHandler({
allowedOrigins: [
'https://app.example.com',
'https://mobile.example.com'
],
credentials: true,
exposedHeaders: ['X-Total-Count', 'X-RateLimit-Remaining'],
maxAge: 7200
});
app.use('/api', corsHandler.middleware());
CORS headers form a critical component of web security, enabling secure cross-origin communication while protecting against unauthorized access. Proper implementation requires understanding both the security implications and the functional requirements of your application. By following security best practices, validating origins against a whitelist, and never trusting user input, you can leverage CORS to build secure, interoperable web applications that safely share resources across origins.## Security Headers for Authentication and Sessions
Authentication and session management represent critical attack vectors in web applications, requiring specialized security headers to protect against session hijacking, credential theft, and authentication bypass attacks. While headers like Set-Cookie with security attributes aren't traditionally grouped with security headers, they play a fundamental role in protecting user sessions. This chapter explores comprehensive security header strategies for authentication systems, session management, and credential protection.