Auth Implementation Patterns
Build secure auth systems with JWT, OAuth2, RBAC, and session patterns
✨ The solution you've been looking for
Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.
See It In Action
Interactive preview & real-world examples
AI Conversation Simulator
See how users interact with this skill
User Prompt
Help me implement JWT authentication for my Node.js API with refresh token rotation and secure middleware
Skill Processing
Analyzing request...
Agent Response
Complete JWT implementation with token generation, verification middleware, refresh flow, and security best practices
Quick Start (3 Steps)
Get up and running in minutes
Install
claude-code skill install auth-implementation-patterns
claude-code skill install auth-implementation-patternsConfig
First Trigger
@auth-implementation-patterns helpCommands
| Command | Description | Required Args |
|---|---|---|
| @auth-implementation-patterns implementing-jwt-authentication | Set up secure JWT-based authentication with access and refresh tokens for a REST API | None |
| @auth-implementation-patterns oauth2-social-login-integration | Add Google and GitHub social login using OAuth2 with Passport.js | None |
| @auth-implementation-patterns role-based-access-control | Design and implement RBAC with permission hierarchies and resource ownership | None |
Typical Use Cases
Implementing JWT Authentication
Set up secure JWT-based authentication with access and refresh tokens for a REST API
OAuth2 Social Login Integration
Add Google and GitHub social login using OAuth2 with Passport.js
Role-Based Access Control
Design and implement RBAC with permission hierarchies and resource ownership
Overview
Authentication & Authorization Implementation Patterns
Build secure, scalable authentication and authorization systems using industry-standard patterns and modern best practices.
When to Use This Skill
- Implementing user authentication systems
- Securing REST or GraphQL APIs
- Adding OAuth2/social login
- Implementing role-based access control (RBAC)
- Designing session management
- Migrating authentication systems
- Debugging auth issues
- Implementing SSO or multi-tenancy
Core Concepts
1. Authentication vs Authorization
Authentication (AuthN): Who are you?
- Verifying identity (username/password, OAuth, biometrics)
- Issuing credentials (sessions, tokens)
- Managing login/logout
Authorization (AuthZ): What can you do?
- Permission checking
- Role-based access control (RBAC)
- Resource ownership validation
- Policy enforcement
2. Authentication Strategies
Session-Based:
- Server stores session state
- Session ID in cookie
- Traditional, simple, stateful
Token-Based (JWT):
- Stateless, self-contained
- Scales horizontally
- Can store claims
OAuth2/OpenID Connect:
- Delegate authentication
- Social login (Google, GitHub)
- Enterprise SSO
JWT Authentication
Pattern 1: JWT Implementation
1// JWT structure: header.payload.signature
2import jwt from "jsonwebtoken";
3import { Request, Response, NextFunction } from "express";
4
5interface JWTPayload {
6 userId: string;
7 email: string;
8 role: string;
9 iat: number;
10 exp: number;
11}
12
13// Generate JWT
14function generateTokens(userId: string, email: string, role: string) {
15 const accessToken = jwt.sign(
16 { userId, email, role },
17 process.env.JWT_SECRET!,
18 { expiresIn: "15m" }, // Short-lived
19 );
20
21 const refreshToken = jwt.sign(
22 { userId },
23 process.env.JWT_REFRESH_SECRET!,
24 { expiresIn: "7d" }, // Long-lived
25 );
26
27 return { accessToken, refreshToken };
28}
29
30// Verify JWT
31function verifyToken(token: string): JWTPayload {
32 try {
33 return jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;
34 } catch (error) {
35 if (error instanceof jwt.TokenExpiredError) {
36 throw new Error("Token expired");
37 }
38 if (error instanceof jwt.JsonWebTokenError) {
39 throw new Error("Invalid token");
40 }
41 throw error;
42 }
43}
44
45// Middleware
46function authenticate(req: Request, res: Response, next: NextFunction) {
47 const authHeader = req.headers.authorization;
48 if (!authHeader?.startsWith("Bearer ")) {
49 return res.status(401).json({ error: "No token provided" });
50 }
51
52 const token = authHeader.substring(7);
53 try {
54 const payload = verifyToken(token);
55 req.user = payload; // Attach user to request
56 next();
57 } catch (error) {
58 return res.status(401).json({ error: "Invalid token" });
59 }
60}
61
62// Usage
63app.get("/api/profile", authenticate, (req, res) => {
64 res.json({ user: req.user });
65});
Pattern 2: Refresh Token Flow
1interface StoredRefreshToken {
2 token: string;
3 userId: string;
4 expiresAt: Date;
5 createdAt: Date;
6}
7
8class RefreshTokenService {
9 // Store refresh token in database
10 async storeRefreshToken(userId: string, refreshToken: string) {
11 const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
12 await db.refreshTokens.create({
13 token: await hash(refreshToken), // Hash before storing
14 userId,
15 expiresAt,
16 });
17 }
18
19 // Refresh access token
20 async refreshAccessToken(refreshToken: string) {
21 // Verify refresh token
22 let payload;
23 try {
24 payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET!) as {
25 userId: string;
26 };
27 } catch {
28 throw new Error("Invalid refresh token");
29 }
30
31 // Check if token exists in database
32 const storedToken = await db.refreshTokens.findOne({
33 where: {
34 token: await hash(refreshToken),
35 userId: payload.userId,
36 expiresAt: { $gt: new Date() },
37 },
38 });
39
40 if (!storedToken) {
41 throw new Error("Refresh token not found or expired");
42 }
43
44 // Get user
45 const user = await db.users.findById(payload.userId);
46 if (!user) {
47 throw new Error("User not found");
48 }
49
50 // Generate new access token
51 const accessToken = jwt.sign(
52 { userId: user.id, email: user.email, role: user.role },
53 process.env.JWT_SECRET!,
54 { expiresIn: "15m" },
55 );
56
57 return { accessToken };
58 }
59
60 // Revoke refresh token (logout)
61 async revokeRefreshToken(refreshToken: string) {
62 await db.refreshTokens.deleteOne({
63 token: await hash(refreshToken),
64 });
65 }
66
67 // Revoke all user tokens (logout all devices)
68 async revokeAllUserTokens(userId: string) {
69 await db.refreshTokens.deleteMany({ userId });
70 }
71}
72
73// API endpoints
74app.post("/api/auth/refresh", async (req, res) => {
75 const { refreshToken } = req.body;
76 try {
77 const { accessToken } =
78 await refreshTokenService.refreshAccessToken(refreshToken);
79 res.json({ accessToken });
80 } catch (error) {
81 res.status(401).json({ error: "Invalid refresh token" });
82 }
83});
84
85app.post("/api/auth/logout", authenticate, async (req, res) => {
86 const { refreshToken } = req.body;
87 await refreshTokenService.revokeRefreshToken(refreshToken);
88 res.json({ message: "Logged out successfully" });
89});
Session-Based Authentication
Pattern 1: Express Session
1import session from "express-session";
2import RedisStore from "connect-redis";
3import { createClient } from "redis";
4
5// Setup Redis for session storage
6const redisClient = createClient({
7 url: process.env.REDIS_URL,
8});
9await redisClient.connect();
10
11app.use(
12 session({
13 store: new RedisStore({ client: redisClient }),
14 secret: process.env.SESSION_SECRET!,
15 resave: false,
16 saveUninitialized: false,
17 cookie: {
18 secure: process.env.NODE_ENV === "production", // HTTPS only
19 httpOnly: true, // No JavaScript access
20 maxAge: 24 * 60 * 60 * 1000, // 24 hours
21 sameSite: "strict", // CSRF protection
22 },
23 }),
24);
25
26// Login
27app.post("/api/auth/login", async (req, res) => {
28 const { email, password } = req.body;
29
30 const user = await db.users.findOne({ email });
31 if (!user || !(await verifyPassword(password, user.passwordHash))) {
32 return res.status(401).json({ error: "Invalid credentials" });
33 }
34
35 // Store user in session
36 req.session.userId = user.id;
37 req.session.role = user.role;
38
39 res.json({ user: { id: user.id, email: user.email, role: user.role } });
40});
41
42// Session middleware
43function requireAuth(req: Request, res: Response, next: NextFunction) {
44 if (!req.session.userId) {
45 return res.status(401).json({ error: "Not authenticated" });
46 }
47 next();
48}
49
50// Protected route
51app.get("/api/profile", requireAuth, async (req, res) => {
52 const user = await db.users.findById(req.session.userId);
53 res.json({ user });
54});
55
56// Logout
57app.post("/api/auth/logout", (req, res) => {
58 req.session.destroy((err) => {
59 if (err) {
60 return res.status(500).json({ error: "Logout failed" });
61 }
62 res.clearCookie("connect.sid");
63 res.json({ message: "Logged out successfully" });
64 });
65});
OAuth2 / Social Login
Pattern 1: OAuth2 with Passport.js
1import passport from "passport";
2import { Strategy as GoogleStrategy } from "passport-google-oauth20";
3import { Strategy as GitHubStrategy } from "passport-github2";
4
5// Google OAuth
6passport.use(
7 new GoogleStrategy(
8 {
9 clientID: process.env.GOOGLE_CLIENT_ID!,
10 clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
11 callbackURL: "/api/auth/google/callback",
12 },
13 async (accessToken, refreshToken, profile, done) => {
14 try {
15 // Find or create user
16 let user = await db.users.findOne({
17 googleId: profile.id,
18 });
19
20 if (!user) {
21 user = await db.users.create({
22 googleId: profile.id,
23 email: profile.emails?.[0]?.value,
24 name: profile.displayName,
25 avatar: profile.photos?.[0]?.value,
26 });
27 }
28
29 return done(null, user);
30 } catch (error) {
31 return done(error, undefined);
32 }
33 },
34 ),
35);
36
37// Routes
38app.get(
39 "/api/auth/google",
40 passport.authenticate("google", {
41 scope: ["profile", "email"],
42 }),
43);
44
45app.get(
46 "/api/auth/google/callback",
47 passport.authenticate("google", { session: false }),
48 (req, res) => {
49 // Generate JWT
50 const tokens = generateTokens(req.user.id, req.user.email, req.user.role);
51 // Redirect to frontend with token
52 res.redirect(
53 `${process.env.FRONTEND_URL}/auth/callback?token=${tokens.accessToken}`,
54 );
55 },
56);
Authorization Patterns
Pattern 1: Role-Based Access Control (RBAC)
1enum Role {
2 USER = "user",
3 MODERATOR = "moderator",
4 ADMIN = "admin",
5}
6
7const roleHierarchy: Record<Role, Role[]> = {
8 [Role.ADMIN]: [Role.ADMIN, Role.MODERATOR, Role.USER],
9 [Role.MODERATOR]: [Role.MODERATOR, Role.USER],
10 [Role.USER]: [Role.USER],
11};
12
13function hasRole(userRole: Role, requiredRole: Role): boolean {
14 return roleHierarchy[userRole].includes(requiredRole);
15}
16
17// Middleware
18function requireRole(...roles: Role[]) {
19 return (req: Request, res: Response, next: NextFunction) => {
20 if (!req.user) {
21 return res.status(401).json({ error: "Not authenticated" });
22 }
23
24 if (!roles.some((role) => hasRole(req.user.role, role))) {
25 return res.status(403).json({ error: "Insufficient permissions" });
26 }
27
28 next();
29 };
30}
31
32// Usage
33app.delete(
34 "/api/users/:id",
35 authenticate,
36 requireRole(Role.ADMIN),
37 async (req, res) => {
38 // Only admins can delete users
39 await db.users.delete(req.params.id);
40 res.json({ message: "User deleted" });
41 },
42);
Pattern 2: Permission-Based Access Control
1enum Permission {
2 READ_USERS = "read:users",
3 WRITE_USERS = "write:users",
4 DELETE_USERS = "delete:users",
5 READ_POSTS = "read:posts",
6 WRITE_POSTS = "write:posts",
7}
8
9const rolePermissions: Record<Role, Permission[]> = {
10 [Role.USER]: [Permission.READ_POSTS, Permission.WRITE_POSTS],
11 [Role.MODERATOR]: [
12 Permission.READ_POSTS,
13 Permission.WRITE_POSTS,
14 Permission.READ_USERS,
15 ],
16 [Role.ADMIN]: Object.values(Permission),
17};
18
19function hasPermission(userRole: Role, permission: Permission): boolean {
20 return rolePermissions[userRole]?.includes(permission) ?? false;
21}
22
23function requirePermission(...permissions: Permission[]) {
24 return (req: Request, res: Response, next: NextFunction) => {
25 if (!req.user) {
26 return res.status(401).json({ error: "Not authenticated" });
27 }
28
29 const hasAllPermissions = permissions.every((permission) =>
30 hasPermission(req.user.role, permission),
31 );
32
33 if (!hasAllPermissions) {
34 return res.status(403).json({ error: "Insufficient permissions" });
35 }
36
37 next();
38 };
39}
40
41// Usage
42app.get(
43 "/api/users",
44 authenticate,
45 requirePermission(Permission.READ_USERS),
46 async (req, res) => {
47 const users = await db.users.findAll();
48 res.json({ users });
49 },
50);
Pattern 3: Resource Ownership
1// Check if user owns resource
2async function requireOwnership(
3 resourceType: "post" | "comment",
4 resourceIdParam: string = "id",
5) {
6 return async (req: Request, res: Response, next: NextFunction) => {
7 if (!req.user) {
8 return res.status(401).json({ error: "Not authenticated" });
9 }
10
11 const resourceId = req.params[resourceIdParam];
12
13 // Admins can access anything
14 if (req.user.role === Role.ADMIN) {
15 return next();
16 }
17
18 // Check ownership
19 let resource;
20 if (resourceType === "post") {
21 resource = await db.posts.findById(resourceId);
22 } else if (resourceType === "comment") {
23 resource = await db.comments.findById(resourceId);
24 }
25
26 if (!resource) {
27 return res.status(404).json({ error: "Resource not found" });
28 }
29
30 if (resource.userId !== req.user.userId) {
31 return res.status(403).json({ error: "Not authorized" });
32 }
33
34 next();
35 };
36}
37
38// Usage
39app.put(
40 "/api/posts/:id",
41 authenticate,
42 requireOwnership("post"),
43 async (req, res) => {
44 // User can only update their own posts
45 const post = await db.posts.update(req.params.id, req.body);
46 res.json({ post });
47 },
48);
Security Best Practices
Pattern 1: Password Security
1import bcrypt from "bcrypt";
2import { z } from "zod";
3
4// Password validation schema
5const passwordSchema = z
6 .string()
7 .min(12, "Password must be at least 12 characters")
8 .regex(/[A-Z]/, "Password must contain uppercase letter")
9 .regex(/[a-z]/, "Password must contain lowercase letter")
10 .regex(/[0-9]/, "Password must contain number")
11 .regex(/[^A-Za-z0-9]/, "Password must contain special character");
12
13// Hash password
14async function hashPassword(password: string): Promise<string> {
15 const saltRounds = 12; // 2^12 iterations
16 return bcrypt.hash(password, saltRounds);
17}
18
19// Verify password
20async function verifyPassword(
21 password: string,
22 hash: string,
23): Promise<boolean> {
24 return bcrypt.compare(password, hash);
25}
26
27// Registration with password validation
28app.post("/api/auth/register", async (req, res) => {
29 try {
30 const { email, password } = req.body;
31
32 // Validate password
33 passwordSchema.parse(password);
34
35 // Check if user exists
36 const existingUser = await db.users.findOne({ email });
37 if (existingUser) {
38 return res.status(400).json({ error: "Email already registered" });
39 }
40
41 // Hash password
42 const passwordHash = await hashPassword(password);
43
44 // Create user
45 const user = await db.users.create({
46 email,
47 passwordHash,
48 });
49
50 // Generate tokens
51 const tokens = generateTokens(user.id, user.email, user.role);
52
53 res.status(201).json({
54 user: { id: user.id, email: user.email },
55 ...tokens,
56 });
57 } catch (error) {
58 if (error instanceof z.ZodError) {
59 return res.status(400).json({ error: error.errors[0].message });
60 }
61 res.status(500).json({ error: "Registration failed" });
62 }
63});
Pattern 2: Rate Limiting
1import rateLimit from "express-rate-limit";
2import RedisStore from "rate-limit-redis";
3
4// Login rate limiter
5const loginLimiter = rateLimit({
6 store: new RedisStore({ client: redisClient }),
7 windowMs: 15 * 60 * 1000, // 15 minutes
8 max: 5, // 5 attempts
9 message: "Too many login attempts, please try again later",
10 standardHeaders: true,
11 legacyHeaders: false,
12});
13
14// API rate limiter
15const apiLimiter = rateLimit({
16 windowMs: 60 * 1000, // 1 minute
17 max: 100, // 100 requests per minute
18 standardHeaders: true,
19});
20
21// Apply to routes
22app.post("/api/auth/login", loginLimiter, async (req, res) => {
23 // Login logic
24});
25
26app.use("/api/", apiLimiter);
Best Practices
- Never Store Plain Passwords: Always hash with bcrypt/argon2
- Use HTTPS: Encrypt data in transit
- Short-Lived Access Tokens: 15-30 minutes max
- Secure Cookies: httpOnly, secure, sameSite flags
- Validate All Input: Email format, password strength
- Rate Limit Auth Endpoints: Prevent brute force attacks
- Implement CSRF Protection: For session-based auth
- Rotate Secrets Regularly: JWT secrets, session secrets
- Log Security Events: Login attempts, failed auth
- Use MFA When Possible: Extra security layer
Common Pitfalls
- Weak Passwords: Enforce strong password policies
- JWT in localStorage: Vulnerable to XSS, use httpOnly cookies
- No Token Expiration: Tokens should expire
- Client-Side Auth Checks Only: Always validate server-side
- Insecure Password Reset: Use secure tokens with expiration
- No Rate Limiting: Vulnerable to brute force
- Trusting Client Data: Always validate on server
Resources
- references/jwt-best-practices.md: JWT implementation guide
- references/oauth2-flows.md: OAuth2 flow diagrams and examples
- references/session-security.md: Secure session management
- assets/auth-security-checklist.md: Security review checklist
- assets/password-policy-template.md: Password requirements template
- scripts/token-validator.ts: JWT validation utility
What Users Are Saying
Real feedback from the community
Environment Matrix
Dependencies
Framework Support
Context Window
Security & Privacy
Information
- Author
- wshobson
- Updated
- 2026-01-30
- Category
- system-admin
Related Skills
Auth Implementation Patterns
Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC …
View Details →Api Integration Specialist
Expert in integrating third-party APIs with proper authentication, error handling, rate limiting, …
View Details →Api Integration Specialist
Expert in integrating third-party APIs with proper authentication, error handling, rate limiting, …
View Details →