[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XMXTY3T0DV598Q66V0NCE":3,"skill-same:01M72XMXTY3T0DV598Q66V0NCE":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M72XMXTY3T0DV598Q66V0NCE","auth-implementation-patterns",null,"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.","steph-frtech\u002Fclaude-code-up","steph-frtech","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F198466323?v=4","01M72XD213FVQA2QXRGTJFKHE1","01M72XD227AANJ993SQTNZB1CK",1,"MIT","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fdeveloper-essentials\u002Fskills\u002Fauth-implementation-patterns\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: auth-implementation-patterns\ndescription: 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.\n---\n\n# Authentication & Authorization Implementation Patterns\n\nBuild secure, scalable authentication and authorization systems using industry-standard patterns and modern best practices.\n\n## When to Use This Skill\n\n- Implementing user authentication systems\n- Securing REST or GraphQL APIs\n- Adding OAuth2\u002Fsocial login\n- Implementing role-based access control (RBAC)\n- Designing session management\n- Migrating authentication systems\n- Debugging auth issues\n- Implementing SSO or multi-tenancy\n\n## Core Concepts\n\n### 1. Authentication vs Authorization\n\n**Authentication (AuthN)**: Who are you?\n\n- Verifying identity (username\u002Fpassword, OAuth, biometrics)\n- Issuing credentials (sessions, tokens)\n- Managing login\u002Flogout\n\n**Authorization (AuthZ)**: What can you do?\n\n- Permission checking\n- Role-based access control (RBAC)\n- Resource ownership validation\n- Policy enforcement\n\n### 2. Authentication Strategies\n\n**Session-Based:**\n\n- Server stores session state\n- Session ID in cookie\n- Traditional, simple, stateful\n\n**Token-Based (JWT):**\n\n- Stateless, self-contained\n- Scales horizontally\n- Can store claims\n\n**OAuth2\u002FOpenID Connect:**\n\n- Delegate authentication\n- Social login (Google, GitHub)\n- Enterprise SSO\n\n## JWT Authentication\n\n### Pattern 1: JWT Implementation\n\n```typescript\n\u002F\u002F JWT structure: header.payload.signature\nimport jwt from \"jsonwebtoken\";\nimport { Request, Response, NextFunction } from \"express\";\n\ninterface JWTPayload {\n  userId: string;\n  email: string;\n  role: string;\n  iat: number;\n  exp: number;\n}\n\n\u002F\u002F Generate JWT\nfunction generateTokens(userId: string, email: string, role: string) {\n  const accessToken = jwt.sign(\n    { userId, email, role },\n    process.env.JWT_SECRET!,\n    { expiresIn: \"15m\" }, \u002F\u002F Short-lived\n  );\n\n  const refreshToken = jwt.sign(\n    { userId },\n    process.env.JWT_REFRESH_SECRET!,\n    { expiresIn: \"7d\" }, \u002F\u002F Long-lived\n  );\n\n  return { accessToken, refreshToken };\n}\n\n\u002F\u002F Verify JWT\nfunction verifyToken(token: string): JWTPayload {\n  try {\n    return jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;\n  } catch (error) {\n    if (error instanceof jwt.TokenExpiredError) {\n      throw new Error(\"Token expired\");\n    }\n    if (error instanceof jwt.JsonWebTokenError) {\n      throw new Error(\"Invalid token\");\n    }\n    throw error;\n  }\n}\n\n\u002F\u002F Middleware\nfunction authenticate(req: Request, res: Response, next: NextFunction) {\n  const authHeader = req.headers.authorization;\n  if (!authHeader?.startsWith(\"Bearer \")) {\n    return res.status(401).json({ error: \"No token provided\" });\n  }\n\n  const token = authHeader.substring(7);\n  try {\n    const payload = verifyToken(token);\n    req.user = payload; \u002F\u002F Attach user to request\n    next();\n  } catch (error) {\n    return res.status(401).json({ error: \"Invalid token\" });\n  }\n}\n\n\u002F\u002F Usage\napp.get(\"\u002Fapi\u002Fprofile\", authenticate, (req, res) => {\n  res.json({ user: req.user });\n});\n```\n\n### Pattern 2: Refresh Token Flow\n\n```typescript\ninterface StoredRefreshToken {\n  token: string;\n  userId: string;\n  expiresAt: Date;\n  createdAt: Date;\n}\n\nclass RefreshTokenService {\n  \u002F\u002F Store refresh token in database\n  async storeRefreshToken(userId: string, refreshToken: string) {\n    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);\n    await db.refreshTokens.create({\n      token: await hash(refreshToken), \u002F\u002F Hash before storing\n      userId,\n      expiresAt,\n    });\n  }\n\n  \u002F\u002F Refresh access token\n  async refreshAccessToken(refreshToken: string) {\n    \u002F\u002F Verify refresh token\n    let payload;\n    try {\n      payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET!) as {\n        userId: string;\n      };\n    } catch {\n      throw new Error(\"Invalid refresh token\");\n    }\n\n    \u002F\u002F Check if token exists in database\n    const storedToken = await db.refreshTokens.findOne({\n      where: {\n        token: await hash(refreshToken),\n        userId: payload.userId,\n        expiresAt: { $gt: new Date() },\n      },\n    });\n\n    if (!storedToken) {\n      throw new Error(\"Refresh token not found or expired\");\n    }\n\n    \u002F\u002F Get user\n    const user = await db.users.findById(payload.userId);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n\n    \u002F\u002F Generate new access token\n    const accessToken = jwt.sign(\n      { userId: user.id, email: user.email, role: user.role },\n      process.env.JWT_SECRET!,\n      { expiresIn: \"15m\" },\n    );\n\n    return { accessToken };\n  }\n\n  \u002F\u002F Revoke refresh token (logout)\n  async revokeRefreshToken(refreshToken: string) {\n    await db.refreshTokens.deleteOne({\n      token: await hash(refreshToken),\n    });\n  }\n\n  \u002F\u002F Revoke all user tokens (logout all devices)\n  async revokeAllUserTokens(userId: string) {\n    await db.refreshTokens.deleteMany({ userId });\n  }\n}\n\n\u002F\u002F API endpoints\napp.post(\"\u002Fapi\u002Fauth\u002Frefresh\", async (req, res) => {\n  const { refreshToken } = req.body;\n  try {\n    const { accessToken } =\n      await refreshTokenService.refreshAccessToken(refreshToken);\n    res.json({ accessToken });\n  } catch (error) {\n    res.status(401).json({ error: \"Invalid refresh token\" });\n  }\n});\n\napp.post(\"\u002Fapi\u002Fauth\u002Flogout\", authenticate, async (req, res) => {\n  const { refreshToken } = req.body;\n  await refreshTokenService.revokeRefreshToken(refreshToken);\n  res.json({ message: \"Logged out successfully\" });\n});\n```\n\n## Session-Based Authentication\n\n### Pattern 1: Express Session\n\n```typescript\nimport session from \"express-session\";\nimport RedisStore from \"connect-redis\";\nimport { createClient } from \"redis\";\n\n\u002F\u002F Setup Redis for session storage\nconst redisClient = createClient({\n  url: process.env.REDIS_URL,\n});\nawait redisClient.connect();\n\napp.use(\n  session({\n    store: new RedisStore({ client: redisClient }),\n    secret: process.env.SESSION_SECRET!,\n    resave: false,\n    saveUninitialized: false,\n    cookie: {\n      secure: process.env.NODE_ENV === \"production\", \u002F\u002F HTTPS only\n      httpOnly: true, \u002F\u002F No JavaScript access\n      maxAge: 24 * 60 * 60 * 1000, \u002F\u002F 24 hours\n      sameSite: \"strict\", \u002F\u002F CSRF protection\n    },\n  }),\n);\n\n\u002F\u002F Login\napp.post(\"\u002Fapi\u002Fauth\u002Flogin\", async (req, res) => {\n  const { email, password } = req.body;\n\n  const user = await db.users.findOne({ email });\n  if (!user || !(await verifyPassword(password, user.passwordHash))) {\n    return res.status(401).json({ error: \"Invalid credentials\" });\n  }\n\n  \u002F\u002F Store user in session\n  req.session.userId = user.id;\n  req.session.role = user.role;\n\n  res.json({ user: { id: user.id, email: user.email, role: user.role } });\n});\n\n\u002F\u002F Session middleware\nfunction requireAuth(req: Request, res: Response, next: NextFunction) {\n  if (!req.session.userId) {\n    return res.status(401).json({ error: \"Not authenticated\" });\n  }\n  next();\n}\n\n\u002F\u002F Protected route\napp.get(\"\u002Fapi\u002Fprofile\", requireAuth, async (req, res) => {\n  const user = await db.users.findById(req.session.userId);\n  res.json({ user });\n});\n\n\u002F\u002F Logout\napp.post(\"\u002Fapi\u002Fauth\u002Flogout\", (req, res) => {\n  req.session.destroy((err) => {\n    if (err) {\n      return res.status(500).json({ error: \"Logout failed\" });\n    }\n    res.clearCookie(\"connect.sid\");\n    res.json({ message: \"Logged out successfully\" });\n  });\n});\n```\n\n## OAuth2 \u002F Social Login\n\n### Pattern 1: OAuth2 with Passport.js\n\n```typescript\nimport passport from \"passport\";\nimport { Strategy as GoogleStrategy } from \"passport-google-oauth20\";\nimport { Strategy as GitHubStrategy } from \"passport-github2\";\n\n\u002F\u002F Google OAuth\npassport.use(\n  new GoogleStrategy(\n    {\n      clientID: process.env.GOOGLE_CLIENT_ID!,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,\n      callbackURL: \"\u002Fapi\u002Fauth\u002Fgoogle\u002Fcallback\",\n    },\n    async (accessToken, refreshToken, profile, done) => {\n      try {\n        \u002F\u002F Find or create user\n        let user = await db.users.findOne({\n          googleId: profile.id,\n        });\n\n        if (!user) {\n          user = await db.users.create({\n            googleId: profile.id,\n            email: profile.emails?.[0]?.value,\n            name: profile.displayName,\n            avatar: profile.photos?.[0]?.value,\n          });\n        }\n\n        return done(null, user);\n      } catch (error) {\n        return done(error, undefined);\n      }\n    },\n  ),\n);\n\n\u002F\u002F Routes\napp.get(\n  \"\u002Fapi\u002Fauth\u002Fgoogle\",\n  passport.authenticate(\"google\", {\n    scope: [\"profile\", \"email\"],\n  }),\n);\n\napp.get(\n  \"\u002Fapi\u002Fauth\u002Fgoogle\u002Fcallback\",\n  passport.authenticate(\"google\", { session: false }),\n  (req, res) => {\n    \u002F\u002F Generate JWT\n    const tokens = generateTokens(req.user.id, req.user.email, req.user.role);\n    \u002F\u002F Redirect to frontend with token\n    res.redirect(\n      `${process.env.FRONTEND_URL}\u002Fauth\u002Fcallback?token=${tokens.accessToken}`,\n    );\n  },\n);\n```\n\n## Authorization Patterns\n\n### Pattern 1: Role-Based Access Control (RBAC)\n\n```typescript\nenum Role {\n  USER = \"user\",\n  MODERATOR = \"moderator\",\n  ADMIN = \"admin\",\n}\n\nconst roleHierarchy: Record\u003CRole, Role[]> = {\n  [Role.ADMIN]: [Role.ADMIN, Role.MODERATOR, Role.USER],\n  [Role.MODERATOR]: [Role.MODERATOR, Role.USER],\n  [Role.USER]: [Role.USER],\n};\n\nfunction hasRole(userRole: Role, requiredRole: Role): boolean {\n  return roleHierarchy[userRole].includes(requiredRole);\n}\n\n\u002F\u002F Middleware\nfunction requireRole(...roles: Role[]) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return res.status(401).json({ error: \"Not authenticated\" });\n    }\n\n    if (!roles.some((role) => hasRole(req.user.role, role))) {\n      return res.status(403).json({ error: \"Insufficient permissions\" });\n    }\n\n    next();\n  };\n}\n\n\u002F\u002F Usage\napp.delete(\n  \"\u002Fapi\u002Fusers\u002F:id\",\n  authenticate,\n  requireRole(Role.ADMIN),\n  async (req, res) => {\n    \u002F\u002F Only admins can delete users\n    await db.users.delete(req.params.id);\n    res.json({ message: \"User deleted\" });\n  },\n);\n```\n\n### Pattern 2: Permission-Based Access Control\n\n```typescript\nenum Permission {\n  READ_USERS = \"read:users\",\n  WRITE_USERS = \"write:users\",\n  DELETE_USERS = \"delete:users\",\n  READ_POSTS = \"read:posts\",\n  WRITE_POSTS = \"write:posts\",\n}\n\nconst rolePermissions: Record\u003CRole, Permission[]> = {\n  [Role.USER]: [Permission.READ_POSTS, Permission.WRITE_POSTS],\n  [Role.MODERATOR]: [\n    Permission.READ_POSTS,\n    Permission.WRITE_POSTS,\n    Permission.READ_USERS,\n  ],\n  [Role.ADMIN]: Object.values(Permission),\n};\n\nfunction hasPermission(userRole: Role, permission: Permission): boolean {\n  return rolePermissions[userRole]?.includes(permission) ?? false;\n}\n\nfunction requirePermission(...permissions: Permission[]) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return res.status(401).json({ error: \"Not authenticated\" });\n    }\n\n    const hasAllPermissions = permissions.every((permission) =>\n      hasPermission(req.user.role, permission),\n    );\n\n    if (!hasAllPermissions) {\n      return res.status(403).json({ error: \"Insufficient permissions\" });\n    }\n\n    next();\n  };\n}\n\n\u002F\u002F Usage\napp.get(\n  \"\u002Fapi\u002Fusers\",\n  authenticate,\n  requirePermission(Permission.READ_USERS),\n  async (req, res) => {\n    const users = await db.users.findAll();\n    res.json({ users });\n  },\n);\n```\n\n### Pattern 3: Resource Ownership\n\n```typescript\n\u002F\u002F Check if user owns resource\nasync function requireOwnership(\n  resourceType: \"post\" | \"comment\",\n  resourceIdParam: string = \"id\",\n) {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return res.status(401).json({ error: \"Not authenticated\" });\n    }\n\n    const resourceId = req.params[resourceIdParam];\n\n    \u002F\u002F Admins can access anything\n    if (req.user.role === Role.ADMIN) {\n      return next();\n    }\n\n    \u002F\u002F Check ownership\n    let resource;\n    if (resourceType === \"post\") {\n      resource = await db.posts.findById(resourceId);\n    } else if (resourceType === \"comment\") {\n      resource = await db.comments.findById(resourceId);\n    }\n\n    if (!resource) {\n      return res.status(404).json({ error: \"Resource not found\" });\n    }\n\n    if (resource.userId !== req.user.userId) {\n      return res.status(403).json({ error: \"Not authorized\" });\n    }\n\n    next();\n  };\n}\n\n\u002F\u002F Usage\napp.put(\n  \"\u002Fapi\u002Fposts\u002F:id\",\n  authenticate,\n  requireOwnership(\"post\"),\n  async (req, res) => {\n    \u002F\u002F User can only update their own posts\n    const post = await db.posts.update(req.params.id, req.body);\n    res.json({ post });\n  },\n);\n```\n\n## Security Best Practices\n\n### Pattern 1: Password Security\n\n```typescript\nimport bcrypt from \"bcrypt\";\nimport { z } from \"zod\";\n\n\u002F\u002F Password validation schema\nconst passwordSchema = z\n  .string()\n  .min(12, \"Password must be at least 12 characters\")\n  .regex(\u002F[A-Z]\u002F, \"Password must contain uppercase letter\")\n  .regex(\u002F[a-z]\u002F, \"Password must contain lowercase letter\")\n  .regex(\u002F[0-9]\u002F, \"Password must contain number\")\n  .regex(\u002F[^A-Za-z0-9]\u002F, \"Password must contain special character\");\n\n\u002F\u002F Hash password\nasync function hashPassword(password: string): Promise\u003Cstring> {\n  const saltRounds = 12; \u002F\u002F 2^12 iterations\n  return bcrypt.hash(password, saltRounds);\n}\n\n\u002F\u002F Verify password\nasync function verifyPassword(\n  password: string,\n  hash: string,\n): Promise\u003Cboolean> {\n  return bcrypt.compare(password, hash);\n}\n\n\u002F\u002F Registration with password validation\napp.post(\"\u002Fapi\u002Fauth\u002Fregister\", async (req, res) => {\n  try {\n    const { email, password } = req.body;\n\n    \u002F\u002F Validate password\n    passwordSchema.parse(password);\n\n    \u002F\u002F Check if user exists\n    const existingUser = await db.users.findOne({ email });\n    if (existingUser) {\n      return res.status(400).json({ error: \"Email already registered\" });\n    }\n\n    \u002F\u002F Hash password\n    const passwordHash = await hashPassword(password);\n\n    \u002F\u002F Create user\n    const user = await db.users.create({\n      email,\n      passwordHash,\n    });\n\n    \u002F\u002F Generate tokens\n    const tokens = generateTokens(user.id, user.email, user.role);\n\n    res.status(201).json({\n      user: { id: user.id, email: user.email },\n      ...tokens,\n    });\n  } catch (error) {\n    if (error instanceof z.ZodError) {\n      return res.status(400).json({ error: error.errors[0].message });\n    }\n    res.status(500).json({ error: \"Registration failed\" });\n  }\n});\n```\n\n### Pattern 2: Rate Limiting\n\n```typescript\nimport rateLimit from \"express-rate-limit\";\nimport RedisStore from \"rate-limit-redis\";\n\n\u002F\u002F Login rate limiter\nconst loginLimiter = rateLimit({\n  store: new RedisStore({ client: redisClient }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 5, \u002F\u002F 5 attempts\n  message: \"Too many login attempts, please try again later\",\n  standardHeaders: true,\n  legacyHeaders: false,\n});\n\n\u002F\u002F API rate limiter\nconst apiLimiter = rateLimit({\n  windowMs: 60 * 1000, \u002F\u002F 1 minute\n  max: 100, \u002F\u002F 100 requests per minute\n  standardHeaders: true,\n});\n\n\u002F\u002F Apply to routes\napp.post(\"\u002Fapi\u002Fauth\u002Flogin\", loginLimiter, async (req, res) => {\n  \u002F\u002F Login logic\n});\n\napp.use(\"\u002Fapi\u002F\", apiLimiter);\n```\n\n## Best Practices\n\n1. **Never Store Plain Passwords**: Always hash with bcrypt\u002Fargon2\n2. **Use HTTPS**: Encrypt data in transit\n3. **Short-Lived Access Tokens**: 15-30 minutes max\n4. **Secure Cookies**: httpOnly, secure, sameSite flags\n5. **Validate All Input**: Email format, password strength\n6. **Rate Limit Auth Endpoints**: Prevent brute force attacks\n7. **Implement CSRF Protection**: For session-based auth\n8. **Rotate Secrets Regularly**: JWT secrets, session secrets\n9. **Log Security Events**: Login attempts, failed auth\n10. **Use MFA When Possible**: Extra security layer\n\n## Common Pitfalls\n\n- **Weak Passwords**: Enforce strong password policies\n- **JWT in localStorage**: Vulnerable to XSS, use httpOnly cookies\n- **No Token Expiration**: Tokens should expire\n- **Client-Side Auth Checks Only**: Always validate server-side\n- **Insecure Password Reset**: Use secure tokens with expiration\n- **No Rate Limiting**: Vulnerable to brute force\n- **Trusting Client Data**: Always validate on server\n","# Authentication & Authorization Implementation Patterns\n\nBuild secure, scalable authentication and authorization systems using industry-standard patterns and modern best practices.\n\n## When to Use This Skill\n\n- Implementing user authentication systems\n- Securing REST or GraphQL APIs\n- Adding OAuth2\u002Fsocial login\n- Implementing role-based access control (RBAC)\n- Designing session management\n- Migrating authentication systems\n- Debugging auth issues\n- Implementing SSO or multi-tenancy\n\n## Core Concepts\n\n### 1. Authentication vs Authorization\n\n**Authentication (AuthN)**: Who are you?\n\n- Verifying identity (username\u002Fpassword, OAuth, biometrics)\n- Issuing credentials (sessions, tokens)\n- Managing login\u002Flogout\n\n**Authorization (AuthZ)**: What can you do?\n\n- Permission checking\n- Role-based access control (RBAC)\n- Resource ownership validation\n- Policy enforcement\n\n### 2. Authentication Strategies\n\n**Session-Based:**\n\n- Server stores session state\n- Session ID in cookie\n- Traditional, simple, stateful\n\n**Token-Based (JWT):**\n\n- Stateless, self-contained\n- Scales horizontally\n- Can store claims\n\n**OAuth2\u002FOpenID Connect:**\n\n- Delegate authentication\n- Social login (Google, GitHub)\n- Enterprise SSO\n\n## JWT Authentication\n\n### Pattern 1: JWT Implementation\n\n```typescript\n\u002F\u002F JWT structure: header.payload.signature\nimport jwt from \"jsonwebtoken\";\nimport { Request, Response, NextFunction } from \"express\";\n\ninterface JWTPayload {\n  userId: string;\n  email: string;\n  role: string;\n  iat: number;\n  exp: number;\n}\n\n\u002F\u002F Generate JWT\nfunction generateTokens(userId: string, email: string, role: string) {\n  const accessToken = jwt.sign(\n    { userId, email, role },\n    process.env.JWT_SECRET!,\n    { expiresIn: \"15m\" }, \u002F\u002F Short-lived\n  );\n\n  const refreshToken = jwt.sign(\n    { userId },\n    process.env.JWT_REFRESH_SECRET!,\n    { expiresIn: \"7d\" }, \u002F\u002F Long-lived\n  );\n\n  return { accessToken, refreshToken };\n}\n\n\u002F\u002F Verify JWT\nfunction verifyToken(token: string): JWTPayload {\n  try {\n    return jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;\n  } catch (error) {\n    if (error instanceof jwt.TokenExpiredError) {\n      throw new Error(\"Token expired\");\n    }\n    if (error instanceof jwt.JsonWebTokenError) {\n      throw new Error(\"Invalid token\");\n    }\n    throw error;\n  }\n}\n\n\u002F\u002F Middleware\nfunction authenticate(req: Request, res: Response, next: NextFunction) {\n  const authHeader = req.headers.authorization;\n  if (!authHeader?.startsWith(\"Bearer \")) {\n    return res.status(401).json({ error: \"No token provided\" });\n  }\n\n  const token = authHeader.substring(7);\n  try {\n    const payload = verifyToken(token);\n    req.user = payload; \u002F\u002F Attach user to request\n    next();\n  } catch (error) {\n    return res.status(401).json({ error: \"Invalid token\" });\n  }\n}\n\n\u002F\u002F Usage\napp.get(\"\u002Fapi\u002Fprofile\", authenticate, (req, res) => {\n  res.json({ user: req.user });\n});\n```\n\n### Pattern 2: Refresh Token Flow\n\n```typescript\ninterface StoredRefreshToken {\n  token: string;\n  userId: string;\n  expiresAt: Date;\n  createdAt: Date;\n}\n\nclass RefreshTokenService {\n  \u002F\u002F Store refresh token in database\n  async storeRefreshToken(userId: string, refreshToken: string) {\n    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);\n    await db.refreshTokens.create({\n      token: await hash(refreshToken), \u002F\u002F Hash before storing\n      userId,\n      expiresAt,\n    });\n  }\n\n  \u002F\u002F Refresh access token\n  async refreshAccessToken(refreshToken: string) {\n    \u002F\u002F Verify refresh token\n    let payload;\n    try {\n      payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET!) as {\n        userId: string;\n      };\n    } catch {\n      throw new Error(\"Invalid refresh token\");\n    }\n\n    \u002F\u002F Check if token exists in database\n    const storedToken = await db.refreshTokens.findOne({\n      where: {\n        token: await hash(refreshToken),\n        userId: payload.userId,\n        expiresAt: { $gt: new Date() },\n      },\n    });\n\n    if (!storedToken) {\n      throw new Error(\"Refresh token not found or expired\");\n    }\n\n    \u002F\u002F Get user\n    const user = await db.users.findById(payload.userId);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n\n    \u002F\u002F Generate new access token\n    const accessToken = jwt.sign(\n      { userId: user.id, email: user.email, role: user.role },\n      process.env.JWT_SECRET!,\n      { expiresIn: \"15m\" },\n    );\n\n    return { accessToken };\n  }\n\n  \u002F\u002F Revoke refresh token (logout)\n  async revokeRefreshToken(refreshToken: string) {\n    await db.refreshTokens.deleteOne({\n      token: await hash(refreshToken),\n    });\n  }\n\n  \u002F\u002F Revoke all user tokens (logout all devices)\n  async revokeAllUserTokens(userId: string) {\n    await db.refreshTokens.deleteMany({ userId });\n  }\n}\n\n\u002F\u002F API endpoints\napp.post(\"\u002Fapi\u002Fauth\u002Frefresh\", async (req, res) => {\n  const { refreshToken } = req.body;\n  try {\n    const { accessToken } =\n      await refreshTokenService.refreshAccessToken(refreshToken);\n    res.json({ accessToken });\n  } catch (error) {\n    res.status(401).json({ error: \"Invalid refresh token\" });\n  }\n});\n\napp.post(\"\u002Fapi\u002Fauth\u002Flogout\", authenticate, async (req, res) => {\n  const { refreshToken } = req.body;\n  await refreshTokenService.revokeRefreshToken(refreshToken);\n  res.json({ message: \"Logged out successfully\" });\n});\n```\n\n## Session-Based Authentication\n\n### Pattern 1: Express Session\n\n```typescript\nimport session from \"express-session\";\nimport RedisStore from \"connect-redis\";\nimport { createClient } from \"redis\";\n\n\u002F\u002F Setup Redis for session storage\nconst redisClient = createClient({\n  url: process.env.REDIS_URL,\n});\nawait redisClient.connect();\n\napp.use(\n  session({\n    store: new RedisStore({ client: redisClient }),\n    secret: process.env.SESSION_SECRET!,\n    resave: false,\n    saveUninitialized: false,\n    cookie: {\n      secure: process.env.NODE_ENV === \"production\", \u002F\u002F HTTPS only\n      httpOnly: true, \u002F\u002F No JavaScript access\n      maxAge: 24 * 60 * 60 * 1000, \u002F\u002F 24 hours\n      sameSite: \"strict\", \u002F\u002F CSRF protection\n    },\n  }),\n);\n\n\u002F\u002F Login\napp.post(\"\u002Fapi\u002Fauth\u002Flogin\", async (req, res) => {\n  const { email, password } = req.body;\n\n  const user = await db.users.findOne({ email });\n  if (!user || !(await verifyPassword(password, user.passwordHash))) {\n    return res.status(401).json({ error: \"Invalid credentials\" });\n  }\n\n  \u002F\u002F Store user in session\n  req.session.userId = user.id;\n  req.session.role = user.role;\n\n  res.json({ user: { id: user.id, email: user.email, role: user.role } });\n});\n\n\u002F\u002F Session middleware\nfunction requireAuth(req: Request, res: Response, next: NextFunction) {\n  if (!req.session.userId) {\n    return res.status(401).json({ error: \"Not authenticated\" });\n  }\n  next();\n}\n\n\u002F\u002F Protected route\napp.get(\"\u002Fapi\u002Fprofile\", requireAuth, async (req, res) => {\n  const user = await db.users.findById(req.session.userId);\n  res.json({ user });\n});\n\n\u002F\u002F Logout\napp.post(\"\u002Fapi\u002Fauth\u002Flogout\", (req, res) => {\n  req.session.destroy((err) => {\n    if (err) {\n      return res.status(500).json({ error: \"Logout failed\" });\n    }\n    res.clearCookie(\"connect.sid\");\n    res.json({ message: \"Logged out successfully\" });\n  });\n});\n```\n\n## OAuth2 \u002F Social Login\n\n### Pattern 1: OAuth2 with Passport.js\n\n```typescript\nimport passport from \"passport\";\nimport { Strategy as GoogleStrategy } from \"passport-google-oauth20\";\nimport { Strategy as GitHubStrategy } from \"passport-github2\";\n\n\u002F\u002F Google OAuth\npassport.use(\n  new GoogleStrategy(\n    {\n      clientID: process.env.GOOGLE_CLIENT_ID!,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,\n      callbackURL: \"\u002Fapi\u002Fauth\u002Fgoogle\u002Fcallback\",\n    },\n    async (accessToken, refreshToken, profile, done) => {\n      try {\n        \u002F\u002F Find or create user\n        let user = await db.users.findOne({\n          googleId: profile.id,\n        });\n\n        if (!user) {\n          user = await db.users.create({\n            googleId: profile.id,\n            email: profile.emails?.[0]?.value,\n            name: profile.displayName,\n            avatar: profile.photos?.[0]?.value,\n          });\n        }\n\n        return done(null, user);\n      } catch (error) {\n        return done(error, undefined);\n      }\n    },\n  ),\n);\n\n\u002F\u002F Routes\napp.get(\n  \"\u002Fapi\u002Fauth\u002Fgoogle\",\n  passport.authenticate(\"google\", {\n    scope: [\"profile\", \"email\"],\n  }),\n);\n\napp.get(\n  \"\u002Fapi\u002Fauth\u002Fgoogle\u002Fcallback\",\n  passport.authenticate(\"google\", { session: false }),\n  (req, res) => {\n    \u002F\u002F Generate JWT\n    const tokens = generateTokens(req.user.id, req.user.email, req.user.role);\n    \u002F\u002F Redirect to frontend with token\n    res.redirect(\n      `${process.env.FRONTEND_URL}\u002Fauth\u002Fcallback?token=${tokens.accessToken}`,\n    );\n  },\n);\n```\n\n## Authorization Patterns\n\n### Pattern 1: Role-Based Access Control (RBAC)\n\n```typescript\nenum Role {\n  USER = \"user\",\n  MODERATOR = \"moderator\",\n  ADMIN = \"admin\",\n}\n\nconst roleHierarchy: Record\u003CRole, Role[]> = {\n  [Role.ADMIN]: [Role.ADMIN, Role.MODERATOR, Role.USER],\n  [Role.MODERATOR]: [Role.MODERATOR, Role.USER],\n  [Role.USER]: [Role.USER],\n};\n\nfunction hasRole(userRole: Role, requiredRole: Role): boolean {\n  return roleHierarchy[userRole].includes(requiredRole);\n}\n\n\u002F\u002F Middleware\nfunction requireRole(...roles: Role[]) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return res.status(401).json({ error: \"Not authenticated\" });\n    }\n\n    if (!roles.some((role) => hasRole(req.user.role, role))) {\n      return res.status(403).json({ error: \"Insufficient permissions\" });\n    }\n\n    next();\n  };\n}\n\n\u002F\u002F Usage\napp.delete(\n  \"\u002Fapi\u002Fusers\u002F:id\",\n  authenticate,\n  requireRole(Role.ADMIN),\n  async (req, res) => {\n    \u002F\u002F Only admins can delete users\n    await db.users.delete(req.params.id);\n    res.json({ message: \"User deleted\" });\n  },\n);\n```\n\n### Pattern 2: Permission-Based Access Control\n\n```typescript\nenum Permission {\n  READ_USERS = \"read:users\",\n  WRITE_USERS = \"write:users\",\n  DELETE_USERS = \"delete:users\",\n  READ_POSTS = \"read:posts\",\n  WRITE_POSTS = \"write:posts\",\n}\n\nconst rolePermissions: Record\u003CRole, Permission[]> = {\n  [Role.USER]: [Permission.READ_POSTS, Permission.WRITE_POSTS],\n  [Role.MODERATOR]: [\n    Permission.READ_POSTS,\n    Permission.WRITE_POSTS,\n    Permission.READ_USERS,\n  ],\n  [Role.ADMIN]: Object.values(Permission),\n};\n\nfunction hasPermission(userRole: Role, permission: Permission): boolean {\n  return rolePermissions[userRole]?.includes(permission) ?? false;\n}\n\nfunction requirePermission(...permissions: Permission[]) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return res.status(401).json({ error: \"Not authenticated\" });\n    }\n\n    const hasAllPermissions = permissions.every((permission) =>\n      hasPermission(req.user.role, permission),\n    );\n\n    if (!hasAllPermissions) {\n      return res.status(403).json({ error: \"Insufficient permissions\" });\n    }\n\n    next();\n  };\n}\n\n\u002F\u002F Usage\napp.get(\n  \"\u002Fapi\u002Fusers\",\n  authenticate,\n  requirePermission(Permission.READ_USERS),\n  async (req, res) => {\n    const users = await db.users.findAll();\n    res.json({ users });\n  },\n);\n```\n\n### Pattern 3: Resource Ownership\n\n```typescript\n\u002F\u002F Check if user owns resource\nasync function requireOwnership(\n  resourceType: \"post\" | \"comment\",\n  resourceIdParam: string = \"id\",\n) {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return res.status(401).json({ error: \"Not authenticated\" });\n    }\n\n    const resourceId = req.params[resourceIdParam];\n\n    \u002F\u002F Admins can access anything\n    if (req.user.role === Role.ADMIN) {\n      return next();\n    }\n\n    \u002F\u002F Check ownership\n    let resource;\n    if (resourceType === \"post\") {\n      resource = await db.posts.findById(resourceId);\n    } else if (resourceType === \"comment\") {\n      resource = await db.comments.findById(resourceId);\n    }\n\n    if (!resource) {\n      return res.status(404).json({ error: \"Resource not found\" });\n    }\n\n    if (resource.userId !== req.user.userId) {\n      return res.status(403).json({ error: \"Not authorized\" });\n    }\n\n    next();\n  };\n}\n\n\u002F\u002F Usage\napp.put(\n  \"\u002Fapi\u002Fposts\u002F:id\",\n  authenticate,\n  requireOwnership(\"post\"),\n  async (req, res) => {\n    \u002F\u002F User can only update their own posts\n    const post = await db.posts.update(req.params.id, req.body);\n    res.json({ post });\n  },\n);\n```\n\n## Security Best Practices\n\n### Pattern 1: Password Security\n\n```typescript\nimport bcrypt from \"bcrypt\";\nimport { z } from \"zod\";\n\n\u002F\u002F Password validation schema\nconst passwordSchema = z\n  .string()\n  .min(12, \"Password must be at least 12 characters\")\n  .regex(\u002F[A-Z]\u002F, \"Password must contain uppercase letter\")\n  .regex(\u002F[a-z]\u002F, \"Password must contain lowercase letter\")\n  .regex(\u002F[0-9]\u002F, \"Password must contain number\")\n  .regex(\u002F[^A-Za-z0-9]\u002F, \"Password must contain special character\");\n\n\u002F\u002F Hash password\nasync function hashPassword(password: string): Promise\u003Cstring> {\n  const saltRounds = 12; \u002F\u002F 2^12 iterations\n  return bcrypt.hash(password, saltRounds);\n}\n\n\u002F\u002F Verify password\nasync function verifyPassword(\n  password: string,\n  hash: string,\n): Promise\u003Cboolean> {\n  return bcrypt.compare(password, hash);\n}\n\n\u002F\u002F Registration with password validation\napp.post(\"\u002Fapi\u002Fauth\u002Fregister\", async (req, res) => {\n  try {\n    const { email, password } = req.body;\n\n    \u002F\u002F Validate password\n    passwordSchema.parse(password);\n\n    \u002F\u002F Check if user exists\n    const existingUser = await db.users.findOne({ email });\n    if (existingUser) {\n      return res.status(400).json({ error: \"Email already registered\" });\n    }\n\n    \u002F\u002F Hash password\n    const passwordHash = await hashPassword(password);\n\n    \u002F\u002F Create user\n    const user = await db.users.create({\n      email,\n      passwordHash,\n    });\n\n    \u002F\u002F Generate tokens\n    const tokens = generateTokens(user.id, user.email, user.role);\n\n    res.status(201).json({\n      user: { id: user.id, email: user.email },\n      ...tokens,\n    });\n  } catch (error) {\n    if (error instanceof z.ZodError) {\n      return res.status(400).json({ error: error.errors[0].message });\n    }\n    res.status(500).json({ error: \"Registration failed\" });\n  }\n});\n```\n\n### Pattern 2: Rate Limiting\n\n```typescript\nimport rateLimit from \"express-rate-limit\";\nimport RedisStore from \"rate-limit-redis\";\n\n\u002F\u002F Login rate limiter\nconst loginLimiter = rateLimit({\n  store: new RedisStore({ client: redisClient }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 5, \u002F\u002F 5 attempts\n  message: \"Too many login attempts, please try again later\",\n  standardHeaders: true,\n  legacyHeaders: false,\n});\n\n\u002F\u002F API rate limiter\nconst apiLimiter = rateLimit({\n  windowMs: 60 * 1000, \u002F\u002F 1 minute\n  max: 100, \u002F\u002F 100 requests per minute\n  standardHeaders: true,\n});\n\n\u002F\u002F Apply to routes\napp.post(\"\u002Fapi\u002Fauth\u002Flogin\", loginLimiter, async (req, res) => {\n  \u002F\u002F Login logic\n});\n\napp.use(\"\u002Fapi\u002F\", apiLimiter);\n```\n\n## Best Practices\n\n1. **Never Store Plain Passwords**: Always hash with bcrypt\u002Fargon2\n2. **Use HTTPS**: Encrypt data in transit\n3. **Short-Lived Access Tokens**: 15-30 minutes max\n4. **Secure Cookies**: httpOnly, secure, sameSite flags\n5. **Validate All Input**: Email format, password strength\n6. **Rate Limit Auth Endpoints**: Prevent brute force attacks\n7. **Implement CSRF Protection**: For session-based auth\n8. **Rotate Secrets Regularly**: JWT secrets, session secrets\n9. **Log Security Events**: Login attempts, failed auth\n10. **Use MFA When Possible**: Extra security layer\n\n## Common Pitfalls\n\n- **Weak Passwords**: Enforce strong password policies\n- **JWT in localStorage**: Vulnerable to XSS, use httpOnly cookies\n- **No Token Expiration**: Tokens should expire\n- **Client-Side Auth Checks Only**: Always validate server-side\n- **Insecure Password Reset**: Use secure tokens with expiration\n- **No Rate Limiting**: Vulnerable to brute force\n- **Trusting Client Data**: Always validate on server\n",{"name":5,"description":7},"main","900bb95bbe72cdb94af6f5a620aa5081264b7b6d",".claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fdeveloper-essentials\u002Fskills\u002Fauth-implementation-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up#readme","https:\u002F\u002Fgithub.com\u002Fsteph-frtech","2026-05-16 00:03:30",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add steph-frtech\u002Fclaude-code-up --skill auth-implementation-patterns",{"tool":37,"command":38},"bunx","bunx skills add steph-frtech\u002Fclaude-code-up --skill auth-implementation-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add steph-frtech\u002Fclaude-code-up --skill auth-implementation-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fdeveloper-essentials\u002Fskills\u002Fauth-implementation-patterns\u002FSKILL.md",true,[],[46,53,60,67,74,81],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M72Y1BY6X8TX3DS19Y04NEBQ","example","One-line summary of what this skill does","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002Fskills\u002Fexample\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":18},"01M72Y1A38EYR8S9P1MBYDAQTW","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__writing-plans\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M72Y174QSV1B5NV1E4KWHQBR","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M72Y14SQRHHMKG316HGB2CGK","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__test-driven-development\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M72Y127BCPRH3BRKPJC3Q3G2","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__systematic-debugging\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M72Y1090GJA6B67KPD60WPHH","subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__subagent-driven-development\u002FSKILL.md",[],[]]