Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Securityintermediate

Auth Middleware

Share

Create authentication middleware

Works with OpenClaude

You 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 (or fastify, hapi, etc.)
  • Confirm you have a JWT library: npm list jsonwebtoken
  • Check your environment has a .env file with JWT_SECRET defined

Steps

  1. Import jsonwebtoken and extract the token from the Authorization header using Bearer <token> format
  2. Verify the token signature using jwt.verify(token, process.env.JWT_SECRET) to ensure validity and expiration
  3. Decode the token payload to extract user information (id, role, permissions)
  4. Attach the decoded user object to req.user so downstream route handlers can access it
  5. Implement error handling for missing tokens (401), invalid tokens (403), and expired tokens (401)
  6. Create an optional role-based middleware that checks req.user.role against required permissions
  7. Export both the authentication middleware and role checker as separate middleware functions
  8. Apply to routes using app.use(authMiddleware) globally or router.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

Quick Info

CategorySecurity
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
securityauthmiddleware

Install command:

curl -o ~/.claude/skills/auth-middleware.md https://claude-skills-hub.vercel.app/skills/security/auth-middleware.md

Related Security Skills

Other Claude Code skills in the same category — free to download.

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.