Auth Patterns logo

Auth Patterns

Organization
MadAppGang
auth-patterns

Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

Overview

PublisherMadAppGang
Repositoryclaude-code
Skill nameauth-patterns
Stars
281
Forks
26
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by MadAppGang on GitHub. Read the source before you install it.

Installation

Install the Auth Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/MadAppGang/claude-code.git /tmp/claude-code
mkdir -p .claude/skills
cp -r /tmp/claude-code/plugins/dev/skills/backend/auth-patterns .claude/skills/auth-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Auth Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Auth Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Auth Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the Auth Patterns AI skill do?

Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

Why use Auth Patterns on TypingMind?

Because you install it once and use it with any model. Auth Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Auth Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/MadAppGang/claude-code/tree/main/plugins/dev/skills/backend/auth-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Auth Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Auth Patterns?

As many as you like. As long as a model supports skills, you can use Auth Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Auth Patterns AI skill free?

Yes. It is published on GitHub by MadAppGang under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇