Agent skill

Auth Patterns

by MadAppGang in MadAppGang/claude-code

A skill your agent uses when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

MITAuto-check passedBackend & APIs

Install Auth Patterns

skills CLI
$ npx skills add MadAppGang/claude-code --skill auth-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install MadAppGang/claude-code auth-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/MadAppGang/claude-code.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/dev/skills/backend/auth-patterns .claude/skills/auth-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
auth-patterns
GitHub stars
284
Token cost
~2.5k tokens
SKILL.md length
93 words
Files
1
Skills in repo
69
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

  • Implementing authentication (JWT
  • SKILL.md covers Overview, Authentication Methods, Password Security and Authorization Patterns, plus 3 more sections
  • Needs JWT_SECRET and JWT_REFRESH_SECRET
  • Authorization (RBAC

What it does

Auth Patterns is an agent skill from MadAppGang/claude-code. Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Authorization and RBAC and Authentication. The repository describes itself as: claude code plugins marketplace. The licence is MIT.

When your agent uses it

  • Implementing authentication (JWT
  • Authorization (RBAC
  • Password hashing
  • Security best practices for backend services

Example prompts

  • “/auth-patterns”

Requirements

  • A credential in JWT_SECRET
  • A credential in JWT_REFRESH_SECRET

What it can do on your machine

Read from SKILL.md and the folder at commit 6097ad4. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • JWT_SECRET
    • JWT_REFRESH_SECRET
    • GOOGLE_CLIENT_SECRET

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Auth Patterns loads about 2.5k tokens when it runs. Until then it costs about 44 tokens; SKILL.md has 93 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~44
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from MadAppGang/claude-code at commit 6097ad4, republished under its MIT licence (© MadAppGang). 93 words, ~2,521 tokens.

Download SKILL.mdSave it as .claude/skills/auth-patterns/SKILL.md (or your agent's skills folder).
name
auth-patterns
description
Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.
version
1.0.0
keywords
authentication, authorization, JWT, sessions, OAuth, RBAC, ABAC, password hashing, bcrypt, MFA, security
plugin
dev
updated
2026-01-20

Authentication Patterns

Overview

Authentication and authorization patterns for securing backend applications.

Authentication Methods

JWT (JSON Web Tokens)
┌─────────────────────────────────────────────────────────┐
│ Header.Payload.Signature                                │
│                                                         │
│ Header:  { "alg": "HS256", "typ": "JWT" }              │
│ Payload: { "sub": "user123", "exp": 1609459200, ... }  │
│ Signature: HMACSHA256(base64(header) + "." +            │
│            base64(payload), secret)                      │
└─────────────────────────────────────────────────────────┘

Token Structure:

typescript
interface JWTPayload {
  sub: string;      // Subject (user ID)
  iat: number;      // Issued at
  exp: number;      // Expiration
  iss?: string;     // Issuer
  aud?: string;     // Audience
  roles?: string[]; // Custom claims
}

Implementation:

typescript
import jwt from 'jsonwebtoken';

const ACCESS_TOKEN_EXPIRY = '15m';
const REFRESH_TOKEN_EXPIRY = '7d';

function generateTokens(user: User) {
  const accessToken = jwt.sign(
    { sub: user.id, roles: user.roles },
    process.env.JWT_SECRET,
    { expiresIn: ACCESS_TOKEN_EXPIRY }
  );

  const refreshToken = jwt.sign(
    { sub: user.id, type: 'refresh' },
    process.env.JWT_REFRESH_SECRET,
    { expiresIn: REFRESH_TOKEN_EXPIRY }
  );

  return { accessToken, refreshToken };
}

function verifyAccessToken(token: string): JWTPayload {
  return jwt.verify(token, process.env.JWT_SECRET) as JWTPayload;
}
Session-Based Authentication
typescript
// Session storage (Redis recommended for production)
interface Session {
  userId: string;
  createdAt: Date;
  expiresAt: Date;
  userAgent?: string;
  ipAddress?: string;
}

// Login
async function login(email: string, password: string, req: Request) {
  const user = await findUserByEmail(email);
  if (!user || !await verifyPassword(password, user.passwordHash)) {
    throw new AuthError('Invalid credentials');
  }

  const sessionId = generateSecureId();
  await redis.set(`session:${sessionId}`, JSON.stringify({
    userId: user.id,
    createdAt: new Date(),
    expiresAt: addDays(new Date(), 7),
    userAgent: req.headers['user-agent'],
  }), 'EX', 7 * 24 * 60 * 60);

  return sessionId;
}

// Middleware
async function authenticate(req: Request, res: Response, next: NextFunction) {
  const sessionId = req.cookies.session;
  if (!sessionId) return res.status(401).json({ error: 'Unauthorized' });

  const session = await redis.get(`session:${sessionId}`);
  if (!session) return res.status(401).json({ error: 'Session expired' });

  req.user = JSON.parse(session);
  next();
}
OAuth 2.0 / OpenID Connect
┌──────────┐                              ┌──────────────┐
│  Client  │──────1. Auth Request──────▶│    Auth      │
│  (App)   │◀─────2. Auth Code──────────│   Provider   │
│          │──────3. Exchange Code──────▶│  (Google,    │
│          │◀─────4. Access Token───────│   GitHub)    │
│          │──────5. API Requests───────▶│              │
└──────────┘                              └──────────────┘

Implementation with Passport.js:

typescript
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/auth/google/callback',
  },
  async (accessToken, refreshToken, profile, done) => {
    const user = await findOrCreateUser({
      provider: 'google',
      providerId: profile.id,
      email: profile.emails[0].value,
      name: profile.displayName,
    });
    done(null, user);
  }
));

// Routes
app.get('/auth/google', passport.authenticate('google', {
  scope: ['profile', 'email']
}));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => res.redirect('/dashboard')
);

Password Security

Hashing
typescript
import bcrypt from 'bcrypt';

const SALT_ROUNDS = 12;

async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, SALT_ROUNDS);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}
Password Requirements
typescript
const PASSWORD_RULES = {
  minLength: 8,
  maxLength: 128,
  requireUppercase: true,
  requireLowercase: true,
  requireNumber: true,
  requireSpecial: true,
};

function validatePassword(password: string): string[] {
  const errors: string[] = [];

  if (password.length < PASSWORD_RULES.minLength) {
    errors.push(`Password must be at least ${PASSWORD_RULES.minLength} characters`);
  }
  if (PASSWORD_RULES.requireUppercase && !/[A-Z]/.test(password)) {
    errors.push('Password must contain an uppercase letter');
  }
  if (PASSWORD_RULES.requireLowercase && !/[a-z]/.test(password)) {
    errors.push('Password must contain a lowercase letter');
  }
  if (PASSWORD_RULES.requireNumber && !/\d/.test(password)) {
    errors.push('Password must contain a number');
  }
  if (PASSWORD_RULES.requireSpecial && !/[!@#$%^&*]/.test(password)) {
    errors.push('Password must contain a special character');
  }

  return errors;
}

Authorization Patterns

Role-Based Access Control (RBAC)
typescript
type Role = 'admin' | 'editor' | 'viewer';

const PERMISSIONS: Record<Role, string[]> = {
  admin: ['read', 'write', 'delete', 'manage_users'],
  editor: ['read', 'write'],
  viewer: ['read'],
};

function hasPermission(user: User, permission: string): boolean {
  return user.roles.some(role =>
    PERMISSIONS[role]?.includes(permission)
  );
}

// Middleware
function requirePermission(permission: string) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!hasPermission(req.user, permission)) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    next();
  };
}

// Usage
app.delete('/users/:id', requirePermission('manage_users'), deleteUser);
Attribute-Based Access Control (ABAC)
typescript
interface Policy {
  resource: string;
  action: string;
  condition: (user: User, resource: any) => boolean;
}

const policies: Policy[] = [
  {
    resource: 'document',
    action: 'edit',
    condition: (user, doc) =>
      doc.ownerId === user.id || user.roles.includes('admin'),
  },
  {
    resource: 'document',
    action: 'delete',
    condition: (user, doc) =>
      doc.ownerId === user.id,
  },
];

function canPerform(user: User, action: string, resource: string, resourceData: any): boolean {
  const policy = policies.find(p =>
    p.resource === resource && p.action === action
  );
  if (!policy) return false;
  return policy.condition(user, resourceData);
}

Security Best Practices

Token Storage
StorageAccess TokenRefresh Token
MemoryYesNo
HttpOnly CookieYes (CSRF protection needed)Yes
localStorageAvoidNever
sessionStorageLast resortNever
Rate Limiting
typescript
import rateLimit from 'express-rate-limit';

const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // 5 attempts
  message: { error: 'Too many login attempts, try again later' },
  standardHeaders: true,
});

app.post('/auth/login', authLimiter, loginHandler);
Account Lockout
typescript
const MAX_FAILED_ATTEMPTS = 5;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes

async function handleLogin(email: string, password: string) {
  const user = await findUserByEmail(email);

  if (user.lockedUntil && user.lockedUntil > new Date()) {
    throw new AuthError('Account locked. Try again later.');
  }

  if (!await verifyPassword(password, user.passwordHash)) {
    await incrementFailedAttempts(user.id);
    if (user.failedAttempts + 1 >= MAX_FAILED_ATTEMPTS) {
      await lockAccount(user.id, LOCKOUT_DURATION);
    }
    throw new AuthError('Invalid credentials');
  }

  await resetFailedAttempts(user.id);
  return generateTokens(user);
}
Secure Headers
typescript
import helmet from 'helmet';

app.use(helmet());
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'"],
    styleSrc: ["'self'", "'unsafe-inline'"],
  },
}));

Multi-Factor Authentication

TOTP (Time-based One-Time Password)
typescript
import speakeasy from 'speakeasy';
import qrcode from 'qrcode';

// Setup MFA
async function setupMFA(userId: string) {
  const secret = speakeasy.generateSecret({
    name: `MyApp (${user.email})`,
  });

  await saveUserMFASecret(userId, secret.base32);

  const qrCodeUrl = await qrcode.toDataURL(secret.otpauth_url);
  return { secret: secret.base32, qrCode: qrCodeUrl };
}

// Verify MFA code
function verifyMFACode(secret: string, code: string): boolean {
  return speakeasy.totp.verify({
    secret,
    encoding: 'base32',
    token: code,
    window: 1, // Allow 1 step tolerance
  });
}

Refresh Token Rotation

typescript
async function refreshTokens(refreshToken: string) {
  const payload = verifyRefreshToken(refreshToken);

  // Check if token is in blocklist (revoked)
  if (await isTokenRevoked(refreshToken)) {
    throw new AuthError('Token revoked');
  }

  // Revoke old refresh token
  await revokeToken(refreshToken);

  // Generate new tokens
  const user = await findUserById(payload.sub);
  return generateTokens(user);
}

Authentication and authorization patterns for secure applications

© MadAppGang, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in plugins/dev/skills/backend/auth-patterns of MadAppGang/claude-code.

Open the folder on GitHubat commit 6097ad4

Compare with similar skills

Auth Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Auth Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Auth Patterns this skillMadAppGang/claude-code284—~2.5kAutomated safety check: PassMIT
Cognitoitsmostafa/aws-agent-skills1.2k1 repos~2.3kAutomated safety check: PassMIT
Auth Implementation Patternsynulihao/AgentSkillOS61710 repos~4.4kAutomated safety check: PassNone
Configuration Cryptogreenpau/caddy-security2.3k—~3.5kAutomated safety check: PassApache-2.0
Supercheck Security Authsupercheck-io/supercheck215—~1.2kAutomated safety check: PassAGPL-3.0
Bkend Authww-w-ai/bkit-claude-code601—~937Automated safety check: NotesApache-2.0

Similar skills

  • Cognito

    itsmostafa/aws-agent-skills

    AWS Cognito user authentication and authorization service. An agent skill from itsmostafa/aws-agent-skills.

    1.2k GitHub starsUsed in 1 repo~2.3k tokens
    Backend & APIsAuto-check passed
  • Auth Implementation Patterns

    ynulihao/AgentSkillOS

    Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems.

    617 GitHub starsUsed in 10 repos~4.4k tokens
    Backend & APIsAuto-check passed
  • Configuration Crypto

    greenpau/caddy-security

    Configure portal/policy JWT keys, token names and lifetimes, key loading and generation, public-key discovery, and System API encryption keys.

    2.3k GitHub stars~3.5k tokensUpdated 3 days ago
    Backend & APIsAuto-check passed
  • Supercheck Security Auth

    supercheck-io/supercheck

    Work on Supercheck authentication, RBAC, tenant isolation, sessions, API and trigger keys, invitations, project membership, project variables, OAuth, super-admin behavior, SSRF, or…

    215 GitHub stars~1.2k tokensUpdated today
    Backend & APIsAuto-check passed
  • Bkend Auth

    ww-w-ai/bkit-claude-code

    bkend.ai authentication — email/social login, JWT tokens, RBAC, session management.

    601 GitHub stars~937 tokensUpdated 11 days ago
    Backend & APIsAuto-check: notes
  • Authentication

    codewithmukesh/dotnet-claude-kit

    Authentication and authorization for ASP.NET Core. An agent skill from codewithmukesh/dotnet-claude-kit.

    751 GitHub starsUsed in 1 repo~1.9k tokens
    Backend & APIsAuto-check passed

More from MadAppGang/claude-code

All 69 skills in this repo
  • API Spec Analyzer

    MadAppGang/claude-code

    Analyzes API documentation from OpenAPI specs to provide TypeScript interfaces, request/response formats, and implementation guidance.

    284 GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed
  • Content Brief

    MadAppGang/claude-code

    Content brief template and creation methodology for SEO-optimized content.

    284 GitHub starsUsed in 1 repo~959 tokens
    Auto-check passed
  • Context Detection

    MadAppGang/claude-code

    A skill your agent uses when detecting project technology stack from files/configs/directory structure, auto-loading framework-specific skills, or analyzing multi-stack fullstack projects (e.g…

    284 GitHub stars~5.4k tokensUpdated 6 mo ago
    Auto-check passed
  • Content Optimizer

    MadAppGang/claude-code

    On-page SEO optimization techniques including keyword density, meta tags, heading structure, and readability.

    284 GitHub starsUsed in 1 repo~694 tokens
    Auto-check passed
  • Keyword Cluster Builder

    MadAppGang/claude-code

    Techniques for expanding seed keywords and clustering by topic and intent.

    284 GitHub starsUsed in 1 repo~674 tokens
    Auto-check passed
  • Serp Analysis

    MadAppGang/claude-code

    SERP analysis techniques for intent classification, feature identification, and competitive intelligence.

    284 GitHub starsUsed in 1 repo~1k tokens
    Auto-check passed

Categories

Questions about Auth Patterns

What does Auth Patterns do?

A skill your agent uses when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services. Auth Patterns is an agent skill from MadAppGang/claude-code. Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

When should I use Auth Patterns?

Auth Patterns fits situations like: implementing authentication (JWT; authorization (RBAC; password hashing; security best practices for backend services.

How do I install Auth Patterns in Claude Code?

Run `npx skills add MadAppGang/claude-code --skill auth-patterns -a claude-code`. Or copy the skill folder (plugins/dev/skills/backend/auth-patterns in MadAppGang/claude-code) into .claude/skills/auth-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Auth Patterns in Codex?

Run `npx skills add MadAppGang/claude-code --skill auth-patterns -a codex`. Or copy the skill folder (plugins/dev/skills/backend/auth-patterns in MadAppGang/claude-code) into .agents/skills/auth-patterns in your project. Codex loads it when a task matches its description.

Can I use Auth Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add MadAppGang/claude-code --skill auth-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/auth-patterns, .gemini/skills/auth-patterns, .github/skills/auth-patterns and .opencode/skills/auth-patterns in your project.

What does Auth Patterns need to run?

Going by SKILL.md and its folder, Auth Patterns needs credentials named JWT_SECRET, JWT_REFRESH_SECRET and GOOGLE_CLIENT_SECRET. Our summary lists: A credential in JWT_SECRET; A credential in JWT_REFRESH_SECRET.

Does Auth Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Auth Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Auth Patterns use?

Auth Patterns is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Auth Patterns use?

About 2.5k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Auth Patterns?

Skills that share tags, products or a category with Auth Patterns: Cognito (itsmostafa/aws-agent-skills, 1.2k stars), Auth Implementation Patterns (ynulihao/AgentSkillOS, 617 stars), Configuration Crypto (greenpau/caddy-security, 2.3k stars) and Supercheck Security Auth (supercheck-io/supercheck, 215 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Auth Patterns?

MadAppGang (a GitHub organization) maintains it in MadAppGang/claude-code, which has 284 GitHub stars. The repository holds 69 skills in this directory. The repository was last updated on March 15, 2026.

Source: MadAppGang/claude-code on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.