Authentication Patterns logo

Authentication Patterns

CommunityPopular
zebbern
authentication-patterns

Authentication patterns: session vs JWT vs OAuth comparison, provider selection (NextAuth, Clerk, Supabase Auth), security checklist, and common mistakes. Use when implementing auth, reviewing auth flows, or choosing auth providers.

Overview

Publisherzebbern
Repositoryclaude-code-guide
Skill nameauthentication-patterns
Stars
4.6K
Forks
464
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 zebbern on GitHub. Read the source before you install it.

Installation

Install the Authentication 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/zebbern/claude-code-guide.git /tmp/claude-code-guide
mkdir -p .claude/skills
cp -r /tmp/claude-code-guide/skills/authentication-patterns .claude/skills/authentication-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Authentication 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 Authentication 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 Authentication 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 Skill

Reference for implementing secure, production-ready authentication.

WHEN_TO_USE

Apply this skill when implementing authentication in a project, reviewing existing auth flows for security issues, choosing between auth providers, or migrating between auth strategies. Use the security checklist before shipping any auth-related change.

AUTH_APPROACHES

ApproachHow It WorksBest ForDrawbacks
Session-basedServer stores session in DB/Redis, client holds session ID cookieTraditional server-rendered apps, apps needing instant revocationRequires server-side storage, harder to scale horizontally without shared store
JWT (stateless)Server signs token, client sends it on each requestAPI-first apps, microservices, mobile clientsCannot revoke without blocklist, token size grows with claims
OAuth 2.0 / OIDCDelegates auth to external provider (Google, GitHub, etc.)Social login, enterprise SSO, reducing auth responsibilityMore complex flow, depends on external provider availability
Passkeys / WebAuthnCryptographic key pair, no passwordsHigh-security apps, passwordless UXLimited browser support legacy, user education needed

Decision Guide

  • Server-rendered app with simple needs → Session-based
  • SPA or mobile app calling APIs → JWT with refresh token rotation
  • Want social login or SSO → OAuth 2.0 / OIDC
  • Greenfield with modern UX goals → Passkeys + OAuth fallback

JWT_BEST_PRACTICES

Token Lifecycle

Login → Access Token (short-lived) + Refresh Token (long-lived, rotated)
  ├─ Access Token: 15 min expiry, sent via httpOnly cookie or Authorization header
  └─ Refresh Token: 7-30 day expiry, stored in httpOnly secure cookie
       └─ On use: issue new access + new refresh token, invalidate old refresh token

Rules

  • [P0-MUST] Set short expiry on access tokens (15 minutes or less).
  • [P0-MUST] Store tokens in httpOnly, Secure, SameSite=Lax cookies — never in localStorage or sessionStorage.
  • [P0-MUST] Implement refresh token rotation — each refresh token is single-use.
  • [P0-MUST] Maintain a server-side blocklist for revoked refresh tokens.
  • [P1-SHOULD] Include only essential claims in JWT payload (sub, iat, exp, role). Keep it small.
  • [P1-SHOULD] Use asymmetric signing (RS256 or ES256) for distributed systems; symmetric (HS256) for single-service only.
  • [P1-SHOULD] Validate iss, aud, and exp claims on every request.
  • [P2-MAY] Use JWE (encrypted JWT) when token payload contains sensitive data.

Token Storage Comparison

StorageXSS SafeCSRF SafeRecommendation
httpOnly cookieYesNo (needs CSRF token)Recommended
localStorageNoYesNever use for auth tokens
sessionStorageNoYesNever use for auth tokens
In-memory (JS variable)YesYesOK for SPAs, lost on refresh

PROVIDER_PATTERNS

Comparison

ProviderTypeBest ForPricingKey Features
NextAuth / Auth.jsOSS libraryNext.js apps wanting full controlFree80+ providers, DB adapters, self-hosted
ClerkManaged serviceFast launch, pre-built UI, user managementFree tier, then per-MAUDrop-in components, user dashboard, org support
Supabase AuthManaged (part of Supabase)Apps already using Supabase for DB/storageFree tier, then per-MAURow-level security integration, magic links, SSO
LuciaOSS libraryFull control, minimal abstractionFreeSession-based, framework-agnostic, type-safe

When to Use Each

  • NextAuth / Auth.js: You want provider flexibility, self-hosting, and database session control. Best when you need custom flows.
  • Clerk: You want auth done fast with pre-built UI components. Best for MVPs and teams that don't want to build auth UI.
  • Supabase Auth: You're already using Supabase. Auth integrates with RLS policies for row-level security.
  • Lucia: You want a minimal, type-safe session library without framework lock-in.

NextAuth.js Setup Pattern

typescript
// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GitHub({
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    }),
  ],
  callbacks: {
    session({ session, user }) {
      session.user.id = user.id;
      return session;
    },
  },
});

SECURITY_CHECKLIST

Before Shipping Auth

  • Rate limiting: Login endpoint limited to 5-10 attempts per minute per IP.
  • CSRF protection: Anti-CSRF tokens on all state-changing requests (or use SameSite=Lax cookies).
  • Password hashing: Using bcrypt (cost 12+) or argon2id — never MD5, SHA-1, or plain SHA-256.
  • HTTPS only: All auth endpoints served over TLS. Cookies have Secure flag.
  • Input validation: Email format, password length (min 8, max 128), no SQL/NoSQL injection vectors.
  • Account enumeration: Login and registration return the same response whether account exists or not.
  • Session invalidation: Logout invalidates server-side session/refresh token, not just client cookie.
  • MFA support: TOTP (authenticator app) or WebAuthn as second factor for sensitive accounts.
  • Password reset: Time-limited tokens (1 hour), single-use, sent over secure channel.
  • Audit logging: Log auth events (login, logout, failed attempts, password changes) with timestamp and IP.

Password Hashing

typescript
// Using bcrypt
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);
}
typescript
// Using argon2 (preferred for new projects)
import argon2 from "argon2";

async function hashPassword(password: string): Promise<string> {
  return argon2.hash(password, { type: argon2.argon2id });
}

async function verifyPassword(hash: string, password: string): Promise<boolean> {
  return argon2.verify(hash, password);
}

COMMON_MISTAKES

MistakeRiskFix
Storing JWT in localStorageXSS can steal tokensUse httpOnly cookies
Long-lived JWTs (days/weeks)Stolen token is valid for extended period15 min access token + refresh rotation
Missing CSRF protectionAttackers can forge requests from other sitesSameSite=Lax cookies + CSRF token
Weak password requirementsBrute force and credential stuffingMin 8 chars, check against breached password lists
Exposing user existence on loginAccount enumerationGeneric "Invalid credentials" message
Not rotating refresh tokensStolen refresh token grants indefinite accessSingle-use refresh tokens with rotation
Hardcoding secrets in sourceCredential leak via git historyUse environment variables, never commit secrets
Missing rate limiting on loginBrute force attacks5-10 attempts/min per IP, exponential backoff
Rolling your own cryptoSubtle vulnerabilitiesUse established libraries (bcrypt, argon2, jose)
Not validating JWT claimsToken misuse across servicesAlways verify iss, aud, exp

Frequently asked questions

What does the Authentication Patterns AI skill do?

Authentication patterns: session vs JWT vs OAuth comparison, provider selection (NextAuth, Clerk, Supabase Auth), security checklist, and common mistakes. Use when implementing auth, reviewing auth flows, or choosing auth providers.

Why use Authentication Patterns on TypingMind?

Because you install it once and use it with any model. Authentication 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 Authentication Patterns in TypingMind?

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

Which AI models can use Authentication 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 Authentication Patterns?

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

Is the Authentication Patterns AI skill free?

Yes. It is published on GitHub by zebbern 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 👇