1mangesh1/dev-skills-collection/authentication-patterns
Claude Code and agent skill by 1mangesh1/dev-skills-collection
- community
Checking that the SKILL.md file is still in the repository.
Comprehensive authentication and authorization implementation guide. Use when the user asks about JWT tokens, OAuth 2.0 flows, session management, API key auth, SSO setup, SAML, OIDC, password hashing, multi-factor authentication, CSRF protection, token storage, CORS headers, rate limiting auth endpoints, bearer tokens, refresh tokens, OAuth scopes, identity providers, user permissions, role-based access control, attribute-based access control, or any authentication and authorization architecture, implementation, or security patterns.
Install
npx vskill@latest install 1mangesh1/dev-skills-collection/authentication-patternsSKILL.md
Authentication and Authorization Patterns
Reference for implementing authentication in web, mobile, and API applications.
1. JWT (JSON Web Tokens)
Structure
Three Base64URL-encoded parts separated by dots: header.payload.signature.
- Header -- algorithm (
alg) and token type (typ). - Payload -- claims:
sub,iat,exp,iss,aud, plus custom claims. - Signature -- HMAC-SHA256 or RSA/ECDSA over header and payload.
Signing
- Symmetric (HS256) -- shared secret; simple but the secret must live on every verifier.
- Asymmetric (RS256, ES256) -- private key signs, public key verifies. Publish via JWKS endpoint.
Access + Refresh Token Flow
- Client authenticates. Server returns a short-lived access token (5-15 min) and a long-lived refresh token.
- Client sends
Authorization: Bearer <access_token>on each request. - On expiry, client posts the refresh token to a dedicated endpoint to get a new access token.
- Server optionally rotates the refresh token on each use. If revoked/expired, user re-authenticates.
JWT Example (Node.js)
JWT Pitfalls
- JWTs are encoded, not encrypted -- never put secrets in claims.
- Always validate
exp,iss, andaudon the server. - Enforce the expected algorithm to prevent
alg: noneor algorithm-switching attacks.
2. OAuth 2.0 Flows
Authorization Code Flow
For server-side apps. Client gets an authorization code via redirect and exchanges it for tokens server-side.
- Redirect to
GET /authorize?response_type=code&client_id=...&redirect_uri=...&scope=...&state=... - User authenticates and consents. Auth server redirects with
?code=...&state=... - Server exchanges the code:
POST /tokenwithgrant_type=authorization_code, code, client_id, client_secret.
Authorization Code with PKCE
Required for public clients (SPAs, mobile) that cannot store a client secret.
- Generate random
code_verifier, derivecode_challenge = BASE64URL(SHA256(code_verifier)). - Send
code_challengeandcode_challenge_method=S256in the authorize request. - Send
code_verifierin the token exchange. Server verifies the hash matches.
Client Credentials Flow
Machine-to-machine, no user. POST /token with grant_type=client_credentials, client_id, client_secret, scope. Returns an access token directly.
Device Authorization Flow
For input-constrained devices (smart TVs, CLI tools). Device gets a user code and verification URL, user authenticates on another device, device polls until complete.
OAuth Example (Python)
3. Session-Based Authentication
- User submits credentials. Server creates a session, stores it (memory/Redis/database), returns a session ID cookie.
- Browser sends the cookie automatically. Server looks up the session to identify the user.
Cookie Configuration
- HttpOnly -- not accessible to JavaScript. Secure -- HTTPS only. SameSite -- mitigates CSRF.
Session Stores
| Store | Pros | Cons | |
|---|---|---|---|
| Memory | Zero setup | Lost on restart, single-process | |
| Redis | Fast, TTL support, clustered | Extra infrastructure | |
| Database | Durable, queryable | Slower, needs cleanup job |
Sliding vs. Absolute Expiration
- Absolute -- expires at a fixed time. Sliding -- resets on each request. Combine both: slide 30 min with an 8-hour hard cap.
4. API Key Authentication
- Generate with a CSPRNG (
crypto.randomBytes(32),secrets.token_urlsafe(32)). Prefix for identification:sk_live_.... - Store hashed (SHA-256) in the database. Show the raw key to the user once at creation.
- Rotate by allowing a new key before revoking the old one; support an overlap period.
- Best for server-to-server calls and usage tracking. Not suitable as sole auth for user-facing apps.
5. Basic Authentication
Authorization: Basic base64(username:password)
Acceptable: internal services behind VPN over TLS, development environments, webhook shared secrets. Not acceptable: public-facing APIs, anything without HTTPS, anywhere token-based auth is feasible. Always pair with rate limiting.
6. Multi-Factor Authentication
TOTP (Time-Based One-Time Passwords)
- Shared secret provisioned via QR code (
otpauth://URI). Client generates a 6-digit code every 30 seconds. - Server accepts current step +/- 1 for clock skew. Libraries:
pyotp,speakeasy.
WebAuthn / Passkeys
- Phishing-resistant: credential is bound to the origin by the browser.
- Registration: server sends challenge, authenticator creates key pair, public key stored server-side.
- Authentication: server sends challenge, authenticator signs it, server verifies.
- Passkeys sync across devices via platform credential managers.
Guidance
- Offer hashed backup codes. Store MFA secrets encrypted at rest.
- Do not reveal MFA status during login -- check password first, then prompt for second factor.
7. Single Sign-On (SSO)
SAML 2.0
- XML-based, common in enterprise. SP redirects to IdP, IdP posts a signed assertion to the SP's ACS URL.
- Validate signature, audience, timestamps, and InResponseTo on every assertion.
OpenID Connect (OIDC)
- Identity layer on OAuth 2.0. Authorization Code flow returns an
id_token(JWT) with user claims (sub,email,name). - Discovery at
/.well-known/openid-configuration. Verifyid_tokenvia JWKS; validateiss,aud,exp,nonce.
Choosing
- OIDC: simpler, JSON-based, better for modern apps. SAML: entrenched in enterprise; support when customers require it.
8. Password Hashing
| Algorithm | Notes | |
|---|---|---|
| bcrypt | Widely supported, cost factor 12+ recommended | |
| Argon2id | Password Hashing Competition winner, memory-hard | |
| scrypt | Memory-hard, good where Argon2 is unavailable |
Never use MD5, SHA-1, or SHA-256 alone -- these are fast hashes, trivially brute-forced. Never use unsalted hashes.
9. Token Storage in the Browser
| Method | XSS Risk | CSRF Risk | Notes | |
|---|---|---|---|---|
| httpOnly cookie | Low | Medium | Not accessible to JS; pair with SameSite + CSRF | |
| localStorage | High | None | Readable by any script on the page | |
| sessionStorage | High | None | Clears on tab close | |
| In-memory (JS) | Low | None | Lost on refresh; use silent refresh flow |
Recommended: refresh tokens in httpOnly Secure SameSite cookies; access tokens in memory; silent refresh on page load.
10. CORS and Authentication Headers
- Use specific origins (not
*) withAccess-Control-Allow-Credentials: true. - Include
AuthorizationinAccess-Control-Allow-Headers. - Keep allowed origins in server config, not hardcoded.
11. Rate Limiting for Auth Endpoints
- Strict limits on
/login,/token,/register,/password-reset. - Rate limit by both IP and account to counter credential stuffing.
- Return
429 Too Many RequestswithRetry-After. Use exponential backoff lockouts. - Separate auth rate limits from general API limits.
12. Common Vulnerabilities
- Token leakage -- tokens in query strings get logged and leaked via referrer headers. Send in headers or POST bodies. Mask tokens in logs.
- Session fixation -- attacker sets a session ID before login. Mitigate by regenerating the session ID on authentication.
- CSRF -- browser sends cookies automatically. Mitigate with SameSite cookies, anti-CSRF tokens, and Origin/Referer verification.
- Credential stuffing -- breached password lists. Mitigate with rate limiting, MFA, and breach-detection APIs.
- JWT algorithm confusion -- enforce the expected algorithm server-side; reject
alg: none. - Open redirects in OAuth -- validate
redirect_urimatches a pre-registered value exactly.
13. Auth Middleware Patterns
Express (Node.js)
FastAPI (Python)
Next.js (Middleware)
References
- RFC 6749 -- OAuth 2.0 Authorization Framework
- RFC 7519 -- JSON Web Token
- RFC 7636 -- Proof Key for Code Exchange (PKCE)
- RFC 8628 -- Device Authorization Grant
- OpenID Connect Core 1.0
- OWASP Authentication Cheat Sheet
- OWASP Session Management Cheat Sheet
- WebAuthn (W3C)
- NIST SP 800-63B -- Digital Identity Guidelines
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/authentication-patterns/SKILL.md
Popularity
- Repository stars
- 2
- 7-day trend score
- 5
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 24 Mar 2026, 8 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/1mangesh1/dev-skills-collection/authentication-patterns)