Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问许可证需确认审计通过

authentication-patterns身份验证模式

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

294

周安装

12

GitHub Stars

61

下载量

94
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:authentication-patterns(身份验证模式)
来源仓库:https://github.com/melodic-software/claude-code-plugins
仓库路径:skills/authentication-patterns
安装命令:
npx skills add https://github.com/melodic-software/claude-code-plugins --skill authentication-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/melodic-software/claude-code-plugins --skill authentication-patterns

简介

用于安全审计、权限检查和认证流程分析,适合梳理敏感配置与依赖风险。

  • 可辅助排查常见漏洞、生成安全复核清单或分析鉴权逻辑实现。
  • 使用时不能将工具输出直接作为结论,需结合人工判断。
  • 涉及密钥、令牌或生产系统时,应先确认最小权限和操作边界。
  • authentication-patterns 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Authentication Patterns

Comprehensive guidance for implementing secure authentication systems, covering JWT, OAuth 2.0, OIDC, Passkeys, MFA, and session management.

When to Use This Skill

Use this skill when:

  • Implementing JWT-based authentication
  • Setting up OAuth 2.0 or OpenID Connect flows
  • Implementing passwordless authentication (Passkeys/FIDO2)
  • Adding multi-factor authentication (MFA/2FA)
  • Designing session management and secure cookies
  • Implementing SSO (Single Sign-On)
  • Reviewing authentication security
  • Choosing between authentication approaches

Authentication Method Selection

MethodBest ForSecurity LevelUX
Passkeys/WebAuthnPrimary auth, passwordless★★★★★Excellent
OAuth 2.0 + PKCEThird-party login, SPAs★★★★☆Good
JWT + Refresh TokensAPIs, microservices★★★★☆Good
Session CookiesTraditional web apps★★★☆☆Excellent
Password + MFALegacy systems upgrade★★★★☆Moderate

Recommendation: Prefer Passkeys for new applications. Use OAuth 2.0 + PKCE for SPAs. Always add MFA as a second factor.

JWT Best Practices Quick Reference

Algorithm Selection

AlgorithmUse CaseRecommendation
RS256Public key verification, distributed systems✅ Recommended
ES256Smaller tokens, ECDSA-based✅ Recommended
HS256Simple systems, same-party verification⚠️ Use carefully
NoneNever use❌ Prohibited

Token Structure

// Header
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-id-for-rotation"  // Key ID for key rotation
}

// Payload (Claims)
{
  "iss": "https://auth.example.com",  // Issuer
  "sub": "user-123",                   // Subject (user ID)
  "aud": "https://api.example.com",   // Audience
  "exp": 1735300000,                   // Expiration (short-lived)
  "iat": 1735296400,                   // Issued at
  "jti": "unique-token-id",            // JWT ID (for revocation)
  "scope": "read write"                // Permissions
}

Token Lifetimes

Token TypeRecommended LifetimeStorage
Access Token5-15 minutesMemory only
Refresh Token7-30 daysSecure HttpOnly cookie or encrypted storage
ID TokenMatch access tokenMemory only

For detailed JWT security: See JWT Security Reference

OAuth 2.0 Flow Selection

FlowUse CasePKCE Required
Authorization Code + PKCESPAs, mobile apps, web apps✅ Yes
Client CredentialsService-to-serviceN/A
Device AuthorizationSmart TVs, CLI toolsN/A
ImplicitDeprecated - don't useN/A
Resource Owner PasswordDeprecated - don't useN/A

Authorization Code + PKCE Flow

┌──────────┐                              ┌───────────────┐
│  Client  │                              │ Auth Server   │
└────┬─────┘                              └───────┬───────┘
     │                                            │
     │ 1. Generate code_verifier (random)         │
     │    code_challenge = SHA256(code_verifier)  │
     │                                            │
     │ 2. Authorization Request ─────────────────>│
     │    (response_type=code, code_challenge)    │
     │                                            │
     │ 3. User authenticates & consents           │
     │                                            │
     │ 4. <────────── Authorization Code ─────────│
     │                                            │
     │ 5. Token Request ─────────────────────────>│
     │    (code, code_verifier)                   │
     │                                            │
     │ 6. <────────── Access + Refresh Tokens ────│
     └────────────────────────────────────────────┘

For detailed OAuth flows: See OAuth Flows Reference

Passkeys/WebAuthn Quick Start

Passkeys provide phishing-resistant, passwordless authentication using public key cryptography.

Registration Flow

// 1. Get challenge from server
const options = await fetch('/api/webauthn/register/options').then(r => r.json());

// 2. Create credential
const credential = await navigator.credentials.create({
  publicKey: {
    challenge: base64ToBuffer(options.challenge),
    rp: { name: "Example App", id: "example.com" },
    user: {
      id: base64ToBuffer(options.userId),
      name: options.username,
      displayName: options.displayName
    },
    pubKeyCredParams: [
      { type: "public-key", alg: -7 },   // ES256
      { type: "public-key", alg: -257 }  // RS256
    ],
    authenticatorSelection: {
      authenticatorAttachment: "platform",  // or "cross-platform"
      residentKey: "required",              // Discoverable credential
      userVerification: "required"          // Biometric/PIN required
    },
    timeout: 60000
  }
});

// 3. Send credential to server for storage
await fetch('/api/webauthn/register/verify', {
  method: 'POST',
  body: JSON.stringify({
    id: credential.id,
    rawId: bufferToBase64(credential.rawId),
    response: {
      clientDataJSON: bufferToBase64(credential.response.clientDataJSON),
      attestationObject: bufferToBase64(credential.response.attestationObject)
    }
  })
});

For complete Passkeys implementation: See Passkeys Implementation Guide

MFA Implementation Patterns

MFA Methods (by Security)

MethodPhishing ResistantSecurityUX
Passkeys/Security Keys✅ Yes★★★★★Good
Authenticator App (TOTP)❌ No★★★★☆Good
Push Notification⚠️ Partial★★★★☆Excellent
SMS OTP❌ No★★☆☆☆Moderate
Email OTP❌ No★★☆☆☆Moderate

TOTP Implementation

using System.Security.Cryptography;
using OtpNet;  // Install: Otp.NET package

/// <summary>
/// TOTP (Time-based One-Time Password) service for MFA.
/// </summary>
public sealed class TotpService
{
    private const int SecretLength = 20;  // 160 bits

    /// <summary>
    /// Generate a new TOTP secret for user enrollment.
    /// </summary>
    public static string GenerateSecret()
    {
        var secretBytes = RandomNumberGenerator.GetBytes(SecretLength);
        return Base32Encoding.ToString(secretBytes);
    }

    /// <summary>
    /// Generate provisioning URI for authenticator apps (Google Authenticator, etc.)
    /// </summary>
    public static string GetProvisioningUri(string secret, string email, string issuer)
    {
        return $"otpauth://totp/{Uri.EscapeDataString(issuer)}:{Uri.EscapeDataString(email)}" +
               $"?secret={secret}&issuer={Uri.EscapeDataString(issuer)}&algorithm=SHA1&digits=6&period=30";
    }

    /// <summary>
    /// Verify TOTP code during login. Allows 1-step time drift.
    /// </summary>
    public static bool VerifyTotp(string secret, string otp)
    {
        var secretBytes = Base32Encoding.ToBytes(secret);
        var totp = new Totp(secretBytes, step: 30, totpSize: 6);

        // VerificationWindow allows for clock drift (1 step = 30 seconds each direction)
        return totp.VerifyTotp(otp, out _, VerificationWindow.RfcSpecifiedNetworkDelay);
    }
}

Session Management

Secure Cookie Configuration

// ASP.NET Core cookie configuration
app.UseCookiePolicy(new CookiePolicyOptions
{
    HttpOnly = HttpOnlyPolicy.Always,        // Prevent JavaScript access (XSS protection)
    Secure = CookieSecurePolicy.Always,      // HTTPS only
    MinimumSameSitePolicy = SameSiteMode.Lax // CSRF protection (or Strict for more security)
});

// Per-cookie configuration
Response.Cookies.Append("session_id", sessionId, new CookieOptions
{
    HttpOnly = true,             // Prevent JavaScript access
    Secure = true,               // HTTPS only
    SameSite = SameSiteMode.Lax, // CSRF protection
    MaxAge = TimeSpan.FromHours(1),
    Domain = ".example.com",
    Path = "/",
    IsEssential = true           // Required for GDPR essential cookies
});

Session Security Checklist

  • Generate cryptographically random session IDs (128+ bits)
  • Regenerate session ID after authentication
  • Set HttpOnly flag on session cookies
  • Set Secure flag (HTTPS only)
  • Set SameSite attribute (Lax or Strict)
  • Implement session timeout (idle and absolute)
  • Invalidate session on logout (server-side)
  • Bind session to user fingerprint (optional, consider privacy)

Password Security (When Required)

Password Hashing

using System.Security.Cryptography;
using Konscious.Security.Cryptography;  // Install: Konscious.Security.Cryptography.Argon2

/// <summary>
/// Argon2id password hashing service (recommended by OWASP).
/// </summary>
public sealed class PasswordHasher
{
    private const int SaltSize = 16;
    private const int HashSize = 32;
    private const int Iterations = 3;      // time_cost
    private const int MemorySize = 65536;  // 64 MB
    private const int Parallelism = 4;     // threads

    /// <summary>
    /// Hash a password using Argon2id.
    /// </summary>
    public static string HashPassword(string password)
    {
        var salt = RandomNumberGenerator.GetBytes(SaltSize);

        using var argon2 = new Argon2id(System.Text.Encoding.UTF8.GetBytes(password))
        {
            Salt = salt,
            DegreeOfParallelism = Parallelism,
            MemorySize = MemorySize,
            Iterations = Iterations
        };

        var hash = argon2.GetBytes(HashSize);

        // Combine salt + hash for storage
        var combined = new byte[SaltSize + HashSize];
        Buffer.BlockCopy(salt, 0, combined, 0, SaltSize);
        Buffer.BlockCopy(hash, 0, combined, SaltSize, HashSize);

        return Convert.ToBase64String(combined);
    }

    /// <summary>
    /// Verify a password against stored hash.
    /// </summary>
    public static bool VerifyPassword(string password, string storedHash)
    {
        var combined = Convert.FromBase64String(storedHash);
        if (combined.Length != SaltSize + HashSize) return false;

        var salt = combined[..SaltSize];
        var expectedHash = combined[SaltSize..];

        using var argon2 = new Argon2id(System.Text.Encoding.UTF8.GetBytes(password))
        {
            Salt = salt,
            DegreeOfParallelism = Parallelism,
            MemorySize = MemorySize,
            Iterations = Iterations
        };

        var actualHash = argon2.GetBytes(HashSize);

        // Timing-safe comparison
        return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
    }
}

Password Policy

RequirementRecommendation
Minimum length12+ characters
Maximum length128+ characters (prevent DoS)
ComplexityNo arbitrary rules (allow all characters)
Breach checkCheck against known breached passwords
Rate limiting5 attempts, then exponential backoff
Account lockoutTemporary lockout (15-30 min) after failures

Quick Decision Tree

What authentication are you implementing?

  1. New web/mobile app → Passkeys + OAuth 2.0 fallback
  2. SPA with API backend → OAuth 2.0 + PKCE with JWT access tokens
  3. Service-to-service → Client Credentials flow or mTLS
  4. Adding MFA to existing → TOTP authenticator app (minimum), Passkeys (ideal)
  5. Traditional web app → Session cookies + CSRF tokens
  6. CLI/device with no browser → Device Authorization flow

Security Checklist

Token Security

  • Short-lived access tokens (5-15 minutes)
  • Secure refresh token storage
  • Token revocation mechanism
  • Proper token validation (signature, claims, expiry)

OAuth/OIDC Security

  • Use PKCE for all public clients
  • Validate redirect URIs strictly
  • Validate state parameter
  • Validate nonce for OIDC
  • Use exact redirect URI matching

Session Security

  • HttpOnly, Secure, SameSite cookies
  • Session regeneration after auth
  • Proper session invalidation
  • Idle and absolute timeouts

MFA Security

  • MFA on all accounts (enforce or encourage)
  • Secure recovery codes
  • Rate limit MFA attempts
  • Prefer phishing-resistant methods

References

Related Skills

SkillRelationship
authorization-modelsAfter authentication, apply authorization (RBAC, ABAC)
cryptographyUnderlying crypto for tokens and passwords
api-securitySecuring API endpoints with authentication
secure-codingGeneral security patterns

Version History

  • v1.0.0 (2025-12-26): Initial release with JWT, OAuth 2.0, Passkeys, MFA, sessions

Last Updated: 2025-12-26

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.94%
按下载量换算35

Claude

27.3%
按下载量换算26

Cursor

17.6%
按下载量换算17

Gemini CLI

9.99%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills