# Send auth-patterns to your agent
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
## Fast path
- 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.
## Suggested prompts
### New install

```text
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.
```
### Upgrade existing

```text
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.
```
## Machine-readable fields
```json
{
  "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": {
    "downloadUrl": "/downloads/auth-patterns",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=auth-patterns",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "packageFormat": "ZIP package",
    "primaryDoc": "SKILL.md",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "downloadMode": "redirect",
    "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."
      ]
    }
  },
  "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"
  }
}
```
## Documentation

### Auth Patterns — Authentication & Authorization

SECURITY-CRITICAL SKILL — Auth is the front door. Get it wrong and nothing else matters.

### Authentication Methods

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

### Dual-Token Strategy

Short-lived access token + long-lived refresh token:

Client → POST /auth/login → Server
Client ← { access_token, refresh_token }

Client → GET /api/data (Authorization: Bearer <access>) → Server
Client ← 401 Expired

Client → POST /auth/refresh { refresh_token } → Server
Client ← { new_access_token, rotated_refresh_token }

### Token Structure

{
  "header": { "alg": "RS256", "typ": "JWT", "kid": "key-2024-01" },
  "payload": {
    "sub": "user_abc123",
    "iss": "https://auth.example.com",
    "aud": "https://api.example.com",
    "exp": 1700000900,
    "iat": 1700000000,
    "jti": "unique-token-id",
    "roles": ["user"],
    "scope": "read:profile write:profile"
  }
}

### Signing Algorithms

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

Prefer RS256/ES256 in distributed systems.

### Token Storage

StorageXSS SafeCSRF SafeRecommendationhttpOnly cookieYesNo (add CSRF token)Best for web appslocalStorageNoYesAvoid — XSS exposes tokensIn-memoryYesYesGood for SPAs, lost on refresh

Set-Cookie: access_token=eyJ...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=900

### Expiration Strategy

TokenLifetimeRotationAccess token5–15 minutesIssued on refreshRefresh token7–30 daysRotate on every useID tokenMatch access tokenNot refreshed

### OAuth 2.0 Flows

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

Implicit flow is deprecated. Always use Authorization Code + PKCE for public clients.

### PKCE Flow

1. Client generates code_verifier (random 43-128 chars)
2. Client computes code_challenge = BASE64URL(SHA256(code_verifier))
3. Redirect to /authorize?code_challenge=...&code_challenge_method=S256
4. User authenticates, server redirects back with authorization code
5. Client exchanges code + code_verifier for tokens at /token
6. Server verifies SHA256(code_verifier) == code_challenge

### Server-Side Sessions

Client Cookie:  session_id=a1b2c3d4 (opaque, random, no user data)
Server Store:   { "a1b2c3d4": { userId: 123, roles: ["admin"], expiresAt: ... } }

StoreSpeedWhen to UseRedisFastProduction default — TTL support, horizontal scalingPostgreSQLModerateWhen Redis is overkill, need audit trailIn-memoryFastestDevelopment only

### Session Security

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

### Authorization Patterns

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

### RBAC Implementation

const ROLE_PERMISSIONS: Record<string, string[]> = {
  admin:  ["user:read", "user:write", "user:delete", "post:read", "post:write", "post:delete"],
  editor: ["user:read", "post:read", "post:write"],
  viewer: ["user:read", "post:read"],
};

function requirePermission(permission: string) {
  return (req: Request, res: Response, next: NextFunction) => {
    const permissions = ROLE_PERMISSIONS[req.user.role] ?? [];
    if (!permissions.includes(permission)) {
      return res.status(403).json({ error: "Forbidden" });
    }
    next();
  };
}

app.delete("/api/users/:id", requirePermission("user:delete"), deleteUser);

### Password Security

AlgorithmRecommendedMemory-HardNotesArgon2idFirst choiceYesResists GPU/ASIC attacksbcryptYesNoBattle-tested, 72-byte limitscryptYesYesGood alternativePBKDF2AcceptableNoNIST approved, weaker vs GPUSHA-256/MD5NeverNoNot password hashing

NIST 800-63B: Favor length (12+ chars) over complexity rules. Check against breached password lists. Don't force periodic rotation unless breach suspected.

### Multi-Factor Authentication

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

### Security Headers

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

### Common Vulnerabilities

#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

### NEVER Do

#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
## Trust
- Source: tencent
- Verification: Indexed source record
- Publisher: wpank
- Version: 1.0.0
## Source health
- Status: healthy
- Item download looks usable.
- Yavira can redirect you to the upstream package for this item.
- Health scope: item
- Reason: direct_download_ok
- Checked at: 2026-05-04T17:37:19.315Z
- Expires at: 2026-05-11T17:37:19.315Z
- Recommended action: Download for OpenClaw
## Links
- [Detail page](https://openagent3.xyz/skills/auth-patterns)
- [Send to Agent page](https://openagent3.xyz/skills/auth-patterns/agent)
- [JSON manifest](https://openagent3.xyz/skills/auth-patterns/agent.json)
- [Markdown brief](https://openagent3.xyz/skills/auth-patterns/agent.md)
- [Download page](https://openagent3.xyz/downloads/auth-patterns)