Introduction to API Security
APIs are the backbone of modern applications, but they're also prime targets for attackers. Securing your API is crucial for protecting sensitive data and maintaining system integrity.
Authentication and Authorization
API Keys
Simple but limited authentication method:
<CodeBlock codes={[ { code: `// API Key validation middleware const validateApiKey = (req, res, next) => { const apiKey = req.headers['x-api-key'];
if (!apiKey || !isValidApiKey(apiKey)) { return res.status(401).json({ error: 'Invalid API key' }); }
next(); };`, language: "javascript", label: "API Key Validation" } ]} />
Best Practices:
- Rotate keys regularly
- Use different keys for different environments
- Never expose keys in client-side code
- Implement rate limiting per key
JWT (JSON Web Tokens)
More secure and scalable authentication:
<CodeBlock codes={[ { code: `// JWT authentication const jwt = require('jsonwebtoken');
function generateToken(user) { return jwt.sign( { id: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h', issuer: 'your-app', audience: 'your-api' } ); }
function verifyToken(req, res, next) { const token = req.headers.authorization?.split(' ')[1];
try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (error) { res.status(401).json({ error: 'Invalid token' }); } }`, language: "javascript", label: "JWT Implementation" } ]} />
Input Validation
Always validate and sanitize input:
<CodeBlock codes={[ { code: `// Input validation with Joi const Joi = require('joi');
const userSchema = Joi.object({ email: Joi.string().email().required(), password: Joi.string().min(12).required(), age: Joi.number().integer().min(18).max(120) });
app.post('/api/users', (req, res) => { const { error, value } = userSchema.validate(req.body);
if (error) { return res.status(400).json({ error: error.details[0].message }); }
// Process validated data });`, language: "javascript", label: "Input Validation" } ]} />
Rate Limiting
Protect against brute force and DDoS attacks:
<CodeBlock codes={[ { code: `const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs message: 'Too many requests, please try again later', standardHeaders: true, legacyHeaders: false, });
app.use('/api/', limiter);`, language: "javascript", label: "Rate Limiting" } ]} />
CORS Configuration
Properly configure Cross-Origin Resource Sharing:
<CodeBlock codes={[ { code: `const cors = require('cors');
const corsOptions = { origin: process.env.ALLOWED_ORIGINS.split(','), methods: ['GET', 'POST', 'PUT', 'DELETE'], allowedHeaders: ['Content-Type', 'Authorization'], credentials: true, maxAge: 86400 // 24 hours };
app.use(cors(corsOptions));`, language: "javascript", label: "CORS Configuration" } ]} />
Error Handling
Never expose sensitive information in error messages:
<CodeBlock codes={[ { code: `// Secure error handling app.use((err, req, res, next) => { // Log full error for debugging console.error(err);
// Send generic message to client res.status(err.status || 500).json({ error: process.env.NODE_ENV === 'production' ? 'An error occurred' : err.message }); });`, language: "javascript", label: "Error Handling" } ]} />
Security Headers
Implement essential security headers:
- X-Content-Type-Options: Prevent MIME sniffing
- X-Frame-Options: Prevent clickjacking
- Content-Security-Policy: Control resource loading
- Strict-Transport-Security: Enforce HTTPS
API Versioning
Maintain backward compatibility and security:
- Use URL versioning:
/api/v1/users - Deprecate old versions gradually
- Document breaking changes
- Monitor usage of deprecated endpoints
Logging and Monitoring
Track API usage and security events:
- Log all authentication attempts
- Monitor unusual traffic patterns
- Track failed requests
- Set up alerts for suspicious activity
Conclusion
API security is multi-faceted. Implement authentication, validation, rate limiting, and monitoring to create a robust security posture. Regular security audits and updates are essential for maintaining protection.