Skip to main content
skill CX Codex

authentication-patterns · rohitg00 — Claude Code skill: OAuth2, JWT, RBAC

authentication-patterns is a Claude Code skill with authentication and authorization patterns: JWT, OAuth2 with PKCE, role-based access control, and Express middleware. For securing a Node.js backend.

Apache-2.0 ★ 2,858 updated 2026-05-12

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a claude-code
Open on GitHub

What authentication-patterns does

This skill provides TypeScript implementations for protecting Node.js applications. It covers short-lived access tokens (15 minutes) paired with longer-lived refresh tokens (7 days) stored in HTTP-only cookies, authentication middleware that validates tokens and returns appropriate errors, OAuth2 Authorization Code Flow with PKCE for public clients, and a role-based access control model with permission checking at both route and data layers.

Each pattern includes anti-patterns to avoid: storing JWTs in localStorage (XSS vulnerability), using a shared secret across multiple services instead of RS256 with key pairs, skipping claims validation (iss, aud, exp), rolling custom password hashing instead of bcrypt or argon2, and failing to protect against CSRF on cookie-based sessions.

A checklist ensures you don't miss critical details: enforcing short token lifespans, securing cookies with HTTP-only and SameSite flags, implementing token revocation via version counters or blocklists, protecting RBAC at both layers, and avoiding user enumeration by not revealing whether an account exists.

What it helps with

  • Issue short and long-lived tokens with different expiration times
  • Protect routes from unauthenticated requests
  • Set up OAuth2 authorization flow with PKCE for a single-page app
  • Enforce role-based permissions across create, read, update, delete operations
  • Block common vulnerabilities: XSS, user enumeration, secret leakage

Example prompts for the agent

  • Implement OAuth2 callback handler with PKCE verification for our frontend
  • Add authentication middleware to validate tokens on protected endpoints
  • Configure roles so admins have full access, editors can post, viewers read-only

How to install authentication-patterns

1Skills CLI (Vercel)

npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a claude-code

2Manually: put the files in place

~/.claude/skills/authentication-patterns/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/authentication-patterns/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about authentication-patterns

How do I install authentication-patterns in Claude Code?

Run npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a claude-code. The skill will be available at ~/.claude/skills/authentication-patterns/SKILL.md.

What does authentication-patterns include?

JWT token generation and verification (access and refresh), Express middleware for authentication, OAuth2 Authorization Code Flow with PKCE, role-based access control with permission matrices, common anti-patterns, and a security checklist.

Why store refresh tokens in HTTP-only cookies instead of localStorage?

HTTP-only cookies cannot be read by JavaScript, protecting against XSS attacks. Combined with Secure and SameSite flags, they prevent token theft and CSRF attacks in ways localStorage cannot.

Source text

SKILL.md · Apache-2.0
---
name: authentication-patterns
description: Authentication and authorization patterns including OAuth2, JWT, RBAC, session management, and PKCE flows
---

# Authentication Patterns

## JWT Access and Refresh Tokens

```typescript
import jwt from "jsonwebtoken";

interface TokenPayload {
  sub: string;
  email: string;
  roles: string[];
}

function generateTokens(user: User) {
  const accessToken = jwt.sign(
    { sub: user.id, email: user.email, roles: user.roles },
    process.env.JWT_SECRET!,
    { expiresIn: "15m", issuer: "auth-service" }
  );

  const refreshToken = jwt.sign(
    { sub: user.id, tokenVersion: user.tokenVersion },
    process.env.REFRESH_SECRET!,
    { expiresIn: "7d", issuer: "auth-service" }
  );

  return { accessToken, refreshToken };
}

function verifyAccessToken(token: string): TokenPayload {
  return jwt.verify(token, process.env.JWT_SECRET!, {
    issuer: "auth-service",
  }) as TokenPayload;
}
```

Short-lived access tokens (15 minutes) with longer-lived refresh tokens (7 days). Store refresh tokens in HTTP-only cookies.

## Auth Middleware

```typescript
function authenticate(req: Request, res: Response, next: NextFunction) {
  const header = req.headers.authorization;
  if (!header?.startsWith("Bearer ")) {
    return res.status(401).json({ error: "Missing authorization header" });
  }

  try {
    const payload = verifyAccessToken(header.slice(7));
    req.user = payload;
    next();
  } catch (error) {
    if (error instanceof jwt.TokenExpiredError) {
      return res.status(401).json({ error: "Token expired" });
    }
    return res.status(401).json({ error: "Invalid token" });
  }
}

function authorize(...roles: string[]) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user) return res.status(401).json({ error: "Not authenticated" });
    if (!roles.some(role => req.user.roles.includes(role))) {
      return res.status(403).json({ error: "Insufficient permissions" });
    }
    next();
  };
}

app.get("/admin/users", authenticate, authorize("admin"), listUsers);
```

## OAuth2 Authorization Code Flow with PKCE

```typescript
import crypto from "crypto";

function generatePKCE() {
  const verifier = crypto.randomBytes(32).toString("base64url");
  const challenge = crypto
    .createHash("sha256")
    .update(verifier)
    .digest("base64url");
  return { verifier, challenge };
}

app.get("/auth/login", (req, res) => {
  const { verifier, challenge } = generatePKCE();
  req.session.codeVerifier = verifier;

  const params = new URLSearchParams({
    response_type: "code",
    client_id: process.env.OAUTH_CLIENT_ID!,
    redirect_uri: `${process.env.APP_URL}/auth/callback`,
    scope: "openid profile email",
    code_challenge: challenge,
    code_challenge_method: "S256",
    state: crypto.randomBytes(16).toString("hex"),
  });

  res.redirect(`${process.env.OAUTH_AUTHORIZE_URL}?${params}`);
});

app.get("/auth/callback", async (req, res) => {
  const { code } = req.query;

  const tokenResponse = await fetch(process.env.OAUTH_TOKEN_URL!, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code: code as string,
      redirect_uri: `${process.env.APP_URL}/auth/callback`,
      client_id: process.env.OAUTH_CLIENT_ID!,
      code_verifier: req.session.codeVerifier,
    }),
  });

  const tokens = await tokenResponse.json();
  const userInfo = jwt.decode(tokens.id_token);

  req.session.user = { id: userInfo.sub, email: userInfo.email };
  res.redirect("/dashboard");
});
```

## RBAC Model

```typescript
interface Permission {
  resource: string;
  action: "create" | "read" | "update" | "delete";
}

const ROLE_PERMISSIONS: Record<string, Permission[]> = {
  viewer: [
    { resource: "posts", action: "read" },
    { resource: "comments", action: "read" },
  ],
  editor: [
    { resource: "posts", action: "create" },
    { resource: "posts", action: "read" },
    { resource: "posts", action: "update" },
    { resource: "comments", action: "create" },
    { resource: "comments", action: "read" },
  ],
  admin: [
    { resource: "*", action: "create" },
    { resource: "*", action: "read" },
    { resource: "*", action: "update" },
    { resource: "*", action: "delete" },
  ],
};

function hasPermission(roles: string[], resource: string, action: string): boolean {
  return roles.some(role =>
    ROLE_PERMISSIONS[role]?.some(
      p => (p.resource === resource || p.resource === "*") && p.action === action
    )
  );
}
```

## Anti-Patterns

- Storing JWTs in `localStorage` (vulnerable to XSS; use HTTP-only cookies)
- Using symmetric secrets for JWTs across multiple services (use RS256 with key pairs)
- Not validating `iss`, `aud`, and `exp` claims on token verification
- Implementing custom password hashing instead of using bcrypt/argon2
- Missing CSRF protection on cookie-based authentication
- Returning different error messages for "user not found" vs "wrong password" (user enumeration)

## Checklist

- [ ] Access tokens are short-lived (15 minutes or less)
- [ ] Refresh tokens stored in HTTP-only, Secure, SameSite cookies
- [ ] Passwords hashed with bcrypt or argon2 (never MD5/SHA)
- [ ] OAuth2 PKCE flow used for public clients
- [ ] RBAC permissions checked at both route and data access layers
- [ ] Token revocation supported via version counter or blocklist
- [ ] CSRF protection enabled for cookie-based auth
- [ ] Authentication errors do not reveal whether the user exists

© rohitg00 · Apache-2.0 · rohitg00/awesome-claude-code-toolkit

Similar skills

All skills for Backend and APIs →

authentication-patterns by other authors comes first.

authentication-patterns travisjneuman authentication-patterns — a Claude Code skill for authentication and authorization patterns. It comes into play when building login flows, MFA, SSO, or access-control models. CX Codex +1 144installs authentication-patterns zebbern The authentication-patterns skill equips coding agents with auth architecture guides, provider comparisons, and a pre-deployment security checklist. Use it when designing secure login flows. CX Codex +1 ★ 4,719repo stars jwt-authentication pluginagentmarketplace Guides your coding agent in implementing JWT authentication for Node.js, covering token pairs, password hashing, and role checks. CX Codex +1 227installs auth-implementation-patterns Seth Hobson auth-implementation-patterns — a skill for designing authentication and authorization: JWT, OAuth2, sessions, roles. Useful when you build a login flow or fix an access bug. CX Codex +1 19,388installs add-authentication-system davila7 The add-authentication-system command for Claude Code builds an authentication layer for an existing application using a selected sign-in method. It covers user accounts, sessions, access rules, and security controls. CX Codex +1 382installs nodejs-backend bobmatnyc The nodejs-backend skill guides TypeScript backend work with Express or Fastify. Use it for REST APIs, routing, middleware, validation, and database integration. CX Codex +1 307installs nodejs-backend-patterns Seth Hobson nodejs-backend-patterns tells the agent how to build Express and Fastify servers: middleware, error handling, auth, database integration. CX Codex +1 48,535installs api-authentication aj-geddes A skill for API authentication: JWT, OAuth 2.0, API keys and session handling. Useful when you lock down endpoints or build a login flow. CX Codex +1 613installs

From the same set178

The whole set →
monitoring-observability monitoring-observability is a Claude Code skill that adds tracing, metrics, structured logs, and alert rules to Node.js services. It connects application signals to dashboards and SLOs. CX Codex +1 ★ 2,858repo stars database-optimizer database-optimizer — a subagent that diagnoses slow queries, designs indexes, implements partitioning schemes, and plans capacity for PostgreSQL, MySQL, and distributed databases. CX Codex ★ 2,858repo stars accessibility-wcag The accessibility-wcag skill for Claude Code provides WCAG 2.2 patterns for semantic HTML, ARIA dialogs, keyboard navigation, and color contrast. CX Codex +1 ★ 2,858repo stars content-strategist The content-strategist subagent plans SEO content, groups topics into clusters, and connects publishing work to performance metrics. It targets technical products and developer audiences. CX Codex ★ 2,858repo stars real-estate-tech real-estate-tech designs proptech platforms with MLS feeds, PostGIS spatial queries, property valuation models, and listing pipelines. Helps build property search and transaction backends. CX Codex ★ 2,858repo stars error-coordinator error-coordinator — a subagent classifies failures in multi-agent workflows, selects retry or fallback paths, and preserves the context needed for recovery. CX Codex ★ 2,858repo stars performance-engineer performance-engineer — a subagent that finds bottlenecks through measurement, not guesswork. Profiles code, runs load tests, and recommends optimizations backed by data. CX Codex ★ 2,858repo stars feature-engineer feature-engineer designs feature stores, transformation pipelines, and encoding strategies for ML models. Prevents train-serve skew across batch training and online serving. CX Codex ★ 2,858repo stars

Project sponsors

Companies that keep this analytics open