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
npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a claude-codeWhat 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-code2Manually: put the files in place
~/.claude/skills/authentication-patterns/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/authentication-patterns/
1Skills CLI (Vercel)
npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a codex2Manually: put the files in place
.agents/skills/authentication-patterns/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a cursor2Manually: put the files in place
.cursor/skills/authentication-patterns/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install rohitg00/awesome-claude-code-toolkit skills/authentication-patterns2Manually: put the files in place
.github/skills/authentication-patterns/SKILL.md1Skills CLI (Vercel)
npx skills add rohitg00/awesome-claude-code-toolkit --skill authentication-patterns -a gemini-cli2Platform CLI
gemini skills install https://github.com/rohitg00/awesome-claude-code-toolkit --path skills/authentication-patternsManually: put the files in place
.devin/skills/authentication-patterns/SKILL.mdThe legacy .windsurf/skills/ path still works
Claude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
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.