Implement role-based access control
✓Works with OpenClaudeYou are a security engineer implementing role-based access control (RBAC) in a Node.js/Express application using middleware and database-backed role definitions.
What to check first
- Verify your Express version supports async middleware:
npm list express - Check if you have a database connection (PostgreSQL/MongoDB) already configured
- Confirm you have
jsonwebtokeninstalled for token claims:npm list jsonwebtoken
Steps
- Define role and permission schemas in your database (PostgreSQL example:
CREATE TABLE roles (id UUID PRIMARY KEY, name VARCHAR UNIQUE); CREATE TABLE permissions (id UUID PRIMARY KEY, action VARCHAR, resource VARCHAR)) - Create a junction table linking roles to permissions:
CREATE TABLE role_permissions (role_id UUID REFERENCES roles(id), permission_id UUID REFERENCES permissions(id)) - Extract and decode the JWT token from the
Authorizationheader in middleware, storing the user's role claim - Build a permission-checking middleware that queries the database for the user's role and validates against required permissions
- Attach RBAC middleware to protected routes using a guard function that specifies required actions and resources
- Implement a cache layer (Redis or in-memory) to avoid querying permissions on every request for the same roles
- Create helper functions to seed initial roles and permissions into the database during application startup
- Add audit logging to track authorization successes and failures with user ID, role, and attempted resource
Code
const express = require('express');
const jwt = require('jsonwebtoken');
const pool = require('./db'); // Your database connection pool
const app = express();
// Role and permission cache
const permissionCache = new Map();
// Seed roles and permissions (run once on startup)
async function seedRoles() {
try {
await pool.query(`
INSERT INTO roles (id, name) VALUES
('admin-role', 'admin'),
('editor-role', 'editor'),
('viewer-role', 'viewer')
ON CONFLICT DO NOTHING
`);
await pool.query(`
INSERT INTO permissions (id, action, resource) VALUES
('perm-create', 'create', 'article'),
('perm-read', 'read', 'article'),
('perm-update', 'update', 'article'),
('perm-delete', 'delete', 'article')
ON CONFLICT DO NOTHING
`);
await pool.query(`
INSERT INTO role_permissions (role_id, permission_id) VALUES
('admin-role', 'perm-create'),
('admin-role', 'perm-read'),
('admin-role', 'perm-update'),
('admin-role', 'perm-delete'),
('editor-role', 'perm-create'),
('editor-role', 'perm-read'),
('editor-role', 'perm-update'),
('viewer-role', 'perm
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
Auth Middleware
Create authentication middleware
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.