{
  "schemaVersion": "1.0",
  "item": {
    "slug": "auth-patterns",
    "name": "auth-patterns",
    "source": "tencent",
    "type": "skill",
    "category": "AI 智能",
    "sourceUrl": "https://clawhub.ai/wpank/auth-patterns",
    "canonicalUrl": "https://clawhub.ai/wpank/auth-patterns",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/auth-patterns",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=auth-patterns",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "slug": "auth-patterns",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-04T17:37:19.315Z",
      "expiresAt": "2026-05-11T17:37:19.315Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=auth-patterns",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=auth-patterns",
        "contentDisposition": "attachment; filename=\"auth-patterns-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "auth-patterns"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/auth-patterns"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/auth-patterns",
    "agentPageUrl": "https://openagent3.xyz/skills/auth-patterns/agent",
    "manifestUrl": "https://openagent3.xyz/skills/auth-patterns/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/auth-patterns/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Auth Patterns — Authentication & Authorization",
        "body": "SECURITY-CRITICAL SKILL — Auth is the front door. Get it wrong and nothing else matters."
      },
      {
        "title": "Authentication Methods",
        "body": "MethodHow It WorksBest ForJWTSigned token sent with each requestSPAs, microservices, mobile APIsSession-basedServer stores session, client holds cookieTraditional web apps, SSROAuth 2.0Delegated auth via authorization server\"Login with Google/GitHub\", API accessAPI KeysStatic key sent in headerInternal services, public APIsMagic LinksOne-time login link via emailLow-friction onboarding, B2CPasskeys/WebAuthnHardware/biometric challenge-responseHigh-security apps, passwordless"
      },
      {
        "title": "Dual-Token Strategy",
        "body": "Short-lived access token + long-lived refresh token:\n\nClient → POST /auth/login → Server\nClient ← { access_token, refresh_token }\n\nClient → GET /api/data (Authorization: Bearer <access>) → Server\nClient ← 401 Expired\n\nClient → POST /auth/refresh { refresh_token } → Server\nClient ← { new_access_token, rotated_refresh_token }"
      },
      {
        "title": "Token Structure",
        "body": "{\n  \"header\": { \"alg\": \"RS256\", \"typ\": \"JWT\", \"kid\": \"key-2024-01\" },\n  \"payload\": {\n    \"sub\": \"user_abc123\",\n    \"iss\": \"https://auth.example.com\",\n    \"aud\": \"https://api.example.com\",\n    \"exp\": 1700000900,\n    \"iat\": 1700000000,\n    \"jti\": \"unique-token-id\",\n    \"roles\": [\"user\"],\n    \"scope\": \"read:profile write:profile\"\n  }\n}"
      },
      {
        "title": "Signing Algorithms",
        "body": "AlgorithmTypeWhen to UseRS256Asymmetric (RSA)Microservices — only auth server holds private keyES256Asymmetric (ECDSA)Same as RS256, smaller keys and signaturesHS256SymmetricSingle-server apps — all verifiers share secret\n\nPrefer RS256/ES256 in distributed systems."
      },
      {
        "title": "Token Storage",
        "body": "StorageXSS SafeCSRF SafeRecommendationhttpOnly cookieYesNo (add CSRF token)Best for web appslocalStorageNoYesAvoid — XSS exposes tokensIn-memoryYesYesGood for SPAs, lost on refresh\n\nSet-Cookie: access_token=eyJ...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=900"
      },
      {
        "title": "Expiration Strategy",
        "body": "TokenLifetimeRotationAccess token5–15 minutesIssued on refreshRefresh token7–30 daysRotate on every useID tokenMatch access tokenNot refreshed"
      },
      {
        "title": "OAuth 2.0 Flows",
        "body": "FlowClient TypeWhen to UseAuthorization Code + PKCEPublic (SPA, mobile)Default for all public clientsAuthorization CodeConfidential (server)Server-rendered web apps with backendClient CredentialsMachine-to-machineService-to-service, cron jobsDevice CodeInput-constrainedSmart TVs, IoT, CLI on headless servers\n\nImplicit flow is deprecated. Always use Authorization Code + PKCE for public clients."
      },
      {
        "title": "PKCE Flow",
        "body": "1. Client generates code_verifier (random 43-128 chars)\n2. Client computes code_challenge = BASE64URL(SHA256(code_verifier))\n3. Redirect to /authorize?code_challenge=...&code_challenge_method=S256\n4. User authenticates, server redirects back with authorization code\n5. Client exchanges code + code_verifier for tokens at /token\n6. Server verifies SHA256(code_verifier) == code_challenge"
      },
      {
        "title": "Server-Side Sessions",
        "body": "Client Cookie:  session_id=a1b2c3d4 (opaque, random, no user data)\nServer Store:   { \"a1b2c3d4\": { userId: 123, roles: [\"admin\"], expiresAt: ... } }\n\nStoreSpeedWhen to UseRedisFastProduction default — TTL support, horizontal scalingPostgreSQLModerateWhen Redis is overkill, need audit trailIn-memoryFastestDevelopment only"
      },
      {
        "title": "Session Security",
        "body": "ThreatPreventionSession fixationRegenerate session ID after loginSession hijackinghttpOnly + Secure cookies, bind to IP/user-agentCSRFSameSite cookies + CSRF tokensIdle timeoutExpire after 15–30 min inactivityAbsolute timeoutForce re-auth after 8–24 hours"
      },
      {
        "title": "Authorization Patterns",
        "body": "PatternGranularityWhen to UseRBACCoarse (admin, editor, viewer)Most apps — simple role hierarchyABACFine (attributes: dept, time, location)Enterprise — context-dependent accessPermission-basedMedium (post:create, user:delete)APIs — decouple permissions from rolesPolicy-based (OPA/Cedar)FineMicroservices — externalized, auditable rulesReBACFine (owner, member, shared-with)Social apps, Google Drive-style sharing"
      },
      {
        "title": "RBAC Implementation",
        "body": "const ROLE_PERMISSIONS: Record<string, string[]> = {\n  admin:  [\"user:read\", \"user:write\", \"user:delete\", \"post:read\", \"post:write\", \"post:delete\"],\n  editor: [\"user:read\", \"post:read\", \"post:write\"],\n  viewer: [\"user:read\", \"post:read\"],\n};\n\nfunction requirePermission(permission: string) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    const permissions = ROLE_PERMISSIONS[req.user.role] ?? [];\n    if (!permissions.includes(permission)) {\n      return res.status(403).json({ error: \"Forbidden\" });\n    }\n    next();\n  };\n}\n\napp.delete(\"/api/users/:id\", requirePermission(\"user:delete\"), deleteUser);"
      },
      {
        "title": "Password Security",
        "body": "AlgorithmRecommendedMemory-HardNotesArgon2idFirst choiceYesResists GPU/ASIC attacksbcryptYesNoBattle-tested, 72-byte limitscryptYesYesGood alternativePBKDF2AcceptableNoNIST approved, weaker vs GPUSHA-256/MD5NeverNoNot password hashing\n\nNIST 800-63B: Favor length (12+ chars) over complexity rules. Check against breached password lists. Don't force periodic rotation unless breach suspected."
      },
      {
        "title": "Multi-Factor Authentication",
        "body": "FactorSecurityNotesTOTP (Authenticator app)HighOffline-capable, Google Authenticator / AuthyWebAuthn/PasskeysHighestPhishing-resistant, hardware-backedSMS OTPMediumVulnerable to SIM swap — avoid for high-securityHardware keys (FIDO2)HighestYubiKey — best for admin accountsBackup codesLow (fallback)One-time use, generate 10, store hashed"
      },
      {
        "title": "Security Headers",
        "body": "HeaderValueStrict-Transport-Securitymax-age=63072000; includeSubDomains; preloadContent-Security-PolicyRestrict script sources, no inline scriptsX-Content-Type-OptionsnosniffX-Frame-OptionsDENYReferrer-Policystrict-origin-when-cross-originCORSWhitelist specific origins, never * with credentials"
      },
      {
        "title": "Common Vulnerabilities",
        "body": "#VulnerabilityPrevention1Broken authenticationMFA, strong password policy, breach detection2Session fixationRegenerate session ID on login3JWT alg:none attackReject none, validate alg against allowlist4JWT secret brute forceUse RS256/ES256, strong secrets (256+ bits)5CSRFSameSite cookies, CSRF tokens6Credential stuffingRate limiting, breached password check, MFA7Insecure password storageArgon2id/bcrypt, never encrypt (hash instead)8Insecure password resetSigned time-limited tokens, invalidate after use9Open redirectValidate redirect URIs against allowlist10Token leakage in URLSend tokens in headers or httpOnly cookies only11Privilege escalationServer-side role checks on every request12OAuth redirect_uri mismatchExact match redirect URI validation, no wildcards13Timing attacksConstant-time comparison for secrets"
      },
      {
        "title": "NEVER Do",
        "body": "#RuleWhy1NEVER store passwords in plaintext or reversible encryptionOne breach exposes every user2NEVER put tokens in URLs or query parametersLogged by servers, proxies, referrer headers3NEVER use alg: none or allow algorithm switching in JWTsAttacker forges tokens4NEVER trust client-side role/permission claimsUsers can modify any client-side value5NEVER use MD5, SHA-1, or plain SHA-256 for password hashingNo salt, no work factor — cracked in seconds6NEVER skip HTTPS in productionTokens and credentials sent in cleartext7NEVER log tokens, passwords, or secretsLogs are broadly accessible and retained8NEVER use long-lived tokens without rotationA single leak grants indefinite access9NEVER implement your own cryptoUse established libraries — jose, bcrypt, passport10NEVER return different errors for \"user not found\" vs \"wrong password\"Enables user enumeration"
      }
    ],
    "body": "Auth Patterns — Authentication & Authorization\n\nSECURITY-CRITICAL SKILL — Auth is the front door. Get it wrong and nothing else matters.\n\nAuthentication Methods\nMethod\tHow It Works\tBest For\nJWT\tSigned token sent with each request\tSPAs, microservices, mobile APIs\nSession-based\tServer stores session, client holds cookie\tTraditional web apps, SSR\nOAuth 2.0\tDelegated auth via authorization server\t\"Login with Google/GitHub\", API access\nAPI Keys\tStatic key sent in header\tInternal services, public APIs\nMagic Links\tOne-time login link via email\tLow-friction onboarding, B2C\nPasskeys/WebAuthn\tHardware/biometric challenge-response\tHigh-security apps, passwordless\nJWT Patterns\nDual-Token Strategy\n\nShort-lived access token + long-lived refresh token:\n\nClient → POST /auth/login → Server\nClient ← { access_token, refresh_token }\n\nClient → GET /api/data (Authorization: Bearer <access>) → Server\nClient ← 401 Expired\n\nClient → POST /auth/refresh { refresh_token } → Server\nClient ← { new_access_token, rotated_refresh_token }\n\nToken Structure\n{\n  \"header\": { \"alg\": \"RS256\", \"typ\": \"JWT\", \"kid\": \"key-2024-01\" },\n  \"payload\": {\n    \"sub\": \"user_abc123\",\n    \"iss\": \"https://auth.example.com\",\n    \"aud\": \"https://api.example.com\",\n    \"exp\": 1700000900,\n    \"iat\": 1700000000,\n    \"jti\": \"unique-token-id\",\n    \"roles\": [\"user\"],\n    \"scope\": \"read:profile write:profile\"\n  }\n}\n\nSigning Algorithms\nAlgorithm\tType\tWhen to Use\nRS256\tAsymmetric (RSA)\tMicroservices — only auth server holds private key\nES256\tAsymmetric (ECDSA)\tSame as RS256, smaller keys and signatures\nHS256\tSymmetric\tSingle-server apps — all verifiers share secret\n\nPrefer RS256/ES256 in distributed systems.\n\nToken Storage\nStorage\tXSS Safe\tCSRF Safe\tRecommendation\nhttpOnly cookie\tYes\tNo (add CSRF token)\tBest for web apps\nlocalStorage\tNo\tYes\tAvoid — XSS exposes tokens\nIn-memory\tYes\tYes\tGood for SPAs, lost on refresh\nSet-Cookie: access_token=eyJ...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=900\n\nExpiration Strategy\nToken\tLifetime\tRotation\nAccess token\t5–15 minutes\tIssued on refresh\nRefresh token\t7–30 days\tRotate on every use\nID token\tMatch access token\tNot refreshed\nOAuth 2.0 Flows\nFlow\tClient Type\tWhen to Use\nAuthorization Code + PKCE\tPublic (SPA, mobile)\tDefault for all public clients\nAuthorization Code\tConfidential (server)\tServer-rendered web apps with backend\nClient Credentials\tMachine-to-machine\tService-to-service, cron jobs\nDevice Code\tInput-constrained\tSmart TVs, IoT, CLI on headless servers\n\nImplicit flow is deprecated. Always use Authorization Code + PKCE for public clients.\n\nPKCE Flow\n1. Client generates code_verifier (random 43-128 chars)\n2. Client computes code_challenge = BASE64URL(SHA256(code_verifier))\n3. Redirect to /authorize?code_challenge=...&code_challenge_method=S256\n4. User authenticates, server redirects back with authorization code\n5. Client exchanges code + code_verifier for tokens at /token\n6. Server verifies SHA256(code_verifier) == code_challenge\n\nSession Management\nServer-Side Sessions\nClient Cookie:  session_id=a1b2c3d4 (opaque, random, no user data)\nServer Store:   { \"a1b2c3d4\": { userId: 123, roles: [\"admin\"], expiresAt: ... } }\n\nStore\tSpeed\tWhen to Use\nRedis\tFast\tProduction default — TTL support, horizontal scaling\nPostgreSQL\tModerate\tWhen Redis is overkill, need audit trail\nIn-memory\tFastest\tDevelopment only\nSession Security\nThreat\tPrevention\nSession fixation\tRegenerate session ID after login\nSession hijacking\thttpOnly + Secure cookies, bind to IP/user-agent\nCSRF\tSameSite cookies + CSRF tokens\nIdle timeout\tExpire after 15–30 min inactivity\nAbsolute timeout\tForce re-auth after 8–24 hours\nAuthorization Patterns\nPattern\tGranularity\tWhen to Use\nRBAC\tCoarse (admin, editor, viewer)\tMost apps — simple role hierarchy\nABAC\tFine (attributes: dept, time, location)\tEnterprise — context-dependent access\nPermission-based\tMedium (post:create, user:delete)\tAPIs — decouple permissions from roles\nPolicy-based (OPA/Cedar)\tFine\tMicroservices — externalized, auditable rules\nReBAC\tFine (owner, member, shared-with)\tSocial apps, Google Drive-style sharing\nRBAC Implementation\nconst ROLE_PERMISSIONS: Record<string, string[]> = {\n  admin:  [\"user:read\", \"user:write\", \"user:delete\", \"post:read\", \"post:write\", \"post:delete\"],\n  editor: [\"user:read\", \"post:read\", \"post:write\"],\n  viewer: [\"user:read\", \"post:read\"],\n};\n\nfunction requirePermission(permission: string) {\n  return (req: Request, res: Response, next: NextFunction) => {\n    const permissions = ROLE_PERMISSIONS[req.user.role] ?? [];\n    if (!permissions.includes(permission)) {\n      return res.status(403).json({ error: \"Forbidden\" });\n    }\n    next();\n  };\n}\n\napp.delete(\"/api/users/:id\", requirePermission(\"user:delete\"), deleteUser);\n\nPassword Security\nAlgorithm\tRecommended\tMemory-Hard\tNotes\nArgon2id\tFirst choice\tYes\tResists GPU/ASIC attacks\nbcrypt\tYes\tNo\tBattle-tested, 72-byte limit\nscrypt\tYes\tYes\tGood alternative\nPBKDF2\tAcceptable\tNo\tNIST approved, weaker vs GPU\nSHA-256/MD5\tNever\tNo\tNot password hashing\n\nNIST 800-63B: Favor length (12+ chars) over complexity rules. Check against breached password lists. Don't force periodic rotation unless breach suspected.\n\nMulti-Factor Authentication\nFactor\tSecurity\tNotes\nTOTP (Authenticator app)\tHigh\tOffline-capable, Google Authenticator / Authy\nWebAuthn/Passkeys\tHighest\tPhishing-resistant, hardware-backed\nSMS OTP\tMedium\tVulnerable to SIM swap — avoid for high-security\nHardware keys (FIDO2)\tHighest\tYubiKey — best for admin accounts\nBackup codes\tLow (fallback)\tOne-time use, generate 10, store hashed\nSecurity Headers\nHeader\tValue\nStrict-Transport-Security\tmax-age=63072000; includeSubDomains; preload\nContent-Security-Policy\tRestrict script sources, no inline scripts\nX-Content-Type-Options\tnosniff\nX-Frame-Options\tDENY\nReferrer-Policy\tstrict-origin-when-cross-origin\nCORS\tWhitelist specific origins, never * with credentials\nCommon Vulnerabilities\n#\tVulnerability\tPrevention\n1\tBroken authentication\tMFA, strong password policy, breach detection\n2\tSession fixation\tRegenerate session ID on login\n3\tJWT alg:none attack\tReject none, validate alg against allowlist\n4\tJWT secret brute force\tUse RS256/ES256, strong secrets (256+ bits)\n5\tCSRF\tSameSite cookies, CSRF tokens\n6\tCredential stuffing\tRate limiting, breached password check, MFA\n7\tInsecure password storage\tArgon2id/bcrypt, never encrypt (hash instead)\n8\tInsecure password reset\tSigned time-limited tokens, invalidate after use\n9\tOpen redirect\tValidate redirect URIs against allowlist\n10\tToken leakage in URL\tSend tokens in headers or httpOnly cookies only\n11\tPrivilege escalation\tServer-side role checks on every request\n12\tOAuth redirect_uri mismatch\tExact match redirect URI validation, no wildcards\n13\tTiming attacks\tConstant-time comparison for secrets\nNEVER Do\n#\tRule\tWhy\n1\tNEVER store passwords in plaintext or reversible encryption\tOne breach exposes every user\n2\tNEVER put tokens in URLs or query parameters\tLogged by servers, proxies, referrer headers\n3\tNEVER use alg: none or allow algorithm switching in JWTs\tAttacker forges tokens\n4\tNEVER trust client-side role/permission claims\tUsers can modify any client-side value\n5\tNEVER use MD5, SHA-1, or plain SHA-256 for password hashing\tNo salt, no work factor — cracked in seconds\n6\tNEVER skip HTTPS in production\tTokens and credentials sent in cleartext\n7\tNEVER log tokens, passwords, or secrets\tLogs are broadly accessible and retained\n8\tNEVER use long-lived tokens without rotation\tA single leak grants indefinite access\n9\tNEVER implement your own crypto\tUse established libraries — jose, bcrypt, passport\n10\tNEVER return different errors for \"user not found\" vs \"wrong password\"\tEnables user enumeration"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/wpank/auth-patterns",
    "publisherUrl": "https://clawhub.ai/wpank/auth-patterns",
    "owner": "wpank",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/auth-patterns",
    "downloadUrl": "https://openagent3.xyz/downloads/auth-patterns",
    "agentUrl": "https://openagent3.xyz/skills/auth-patterns/agent",
    "manifestUrl": "https://openagent3.xyz/skills/auth-patterns/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/auth-patterns/agent.md"
  }
}