Create authentication middleware
✓Works with OpenClaudeYou are a backend security engineer. The user wants to create authentication middleware that validates incoming requests and protects routes.
What to check first
- Verify your web framework is installed:
npm list express(orfastify,hapi, etc.) - Confirm you have a JWT library:
npm list jsonwebtoken - Check your environment has a
.envfile withJWT_SECRETdefined
Steps
- Import
jsonwebtokenand extract the token from theAuthorizationheader usingBearer <token>format - Verify the token signature using
jwt.verify(token, process.env.JWT_SECRET)to ensure validity and expiration - Decode the token payload to extract user information (id, role, permissions)
- Attach the decoded user object to
req.userso downstream route handlers can access it - Implement error handling for missing tokens (401), invalid tokens (403), and expired tokens (401)
- Create an optional role-based middleware that checks
req.user.roleagainst required permissions - Export both the authentication middleware and role checker as separate middleware functions
- Apply to routes using
app.use(authMiddleware)globally orrouter.get('/protected', authMiddleware, handler)per-route
Code
const express = require('express');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const app = express();
// Core authentication middleware
const authMiddleware = (req, res, next) => {
try {
const authHeader = req.headers.authorization;
// Check if Authorization header exists
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or malformed authorization header' });
}
// Extract token from "Bearer <token>"
const token = authHeader.slice(7);
// Verify and decode the token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Attach user info to request object
req.user = decoded;
next();
} catch (error) {
if (error.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired' });
}
if (error.name === 'JsonWebTokenError') {
return res.status(403).json({ error: 'Invalid token' });
}
return res.status(500).json({ error: 'Authentication error' });
}
};
// Role-based authorization middleware
const requireRole = (allowedRoles) => {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'User not authenticated' });
}
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Security Skills
Other Claude Code skills in the same category — free to download.
Dependency Audit
Audit dependencies for known vulnerabilities
Secret Scanner
Scan codebase for leaked secrets and credentials
CSP Generator
Generate Content Security Policy headers
Input Sanitizer
Add input sanitization to prevent injection attacks
RBAC Setup
Implement role-based access control
CSRF Protection
Add CSRF protection to forms and APIs
Security Headers
Configure security headers (HSTS, X-Frame-Options, etc.)
Encryption Helper
Set up encryption for sensitive data at rest
Want a Security skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.