Authentication Skill
When to use this skill
Use when implementing login/signup, session management, OAuth integrations, role-based access control, or any security-sensitive auth feature.
Auth Principles
1. Never roll your own crypto
- Use established libraries for hashing, tokens, encryption
- Don't invent custom auth protocols
- Follow OWASP guidelines
2. Defense in depth
- Auth at the API gateway / middleware (not per-endpoint)
- Validate tokens on every request
- Never trust the client
3. Least privilege
- Users get minimum permissions needed
- Tokens scope to specific actions
- Admin access is audited
Authentication Patterns
Pattern 1: Session-Based Auth
Client → POST /login (credentials) → Server creates session
Client → requests with session cookie → Server validates session
Client → POST /logout → Server destroys session
Best for: Traditional web apps, server-rendered pages
Rules:
- Store sessions server-side (database or Redis), not in cookies
- Use HTTP-only, Secure, SameSite cookies
- Set session expiry (24h default, configurable)
- Regenerate session ID after login (prevent session fixation)
- Invalidate session on logout and password change
Pattern 2: JWT (JSON Web Token)
Client → POST /login (credentials) → Server returns access + refresh tokens
Client → requests with Authorization: Bearer <access_token>
Client → POST /refresh (refresh_token) → Server returns new access token
Best for: APIs, SPAs, mobile apps, microservices
Rules:
- Access tokens: short-lived (15-30 minutes)
- Refresh tokens: longer-lived (7-30 days), stored securely
- Never store JWTs in localStorage (use HTTP-only cookies or memory)
- Include minimal claims (user ID, role — never sensitive data)
- Validate signature, expiry, and issuer on every request
- Support token revocation (blacklist or short-lived + rotation)
Pattern 3: OAuth 2.0 / OpenID Connect
Client → Redirect to provider → User authenticates → Redirect back with code
Server → Exchange code for tokens → Create local session/JWT
Best for: "Login with Google/GitHub/etc.", third-party integrations
Rules:
- Use Authorization Code Flow with PKCE (not Implicit Flow)
- Validate
state parameter to prevent CSRF
- Validate ID token claims (issuer, audience, expiry)
- Store provider tokens securely if you need to call their APIs
Password Handling
Rules
- Hash passwords with bcrypt, scrypt, or Argon2 — never MD5/SHA
- Salt automatically (bcrypt does this) — never reuse salts
- Minimum password length: 8 characters — prefer 12+
- Check against breached password lists (Have I Been Pwned API)
- Never log passwords — not even hashed ones
- Never send passwords in URLs — always POST body
- Never store plaintext passwords — anywhere, ever
Password reset flow
- User requests reset → generate random token (not the password hash)
- Send token via email → link expires in 1 hour
- User clicks link → verify token, show new password form
- User sets new password → invalidate token, invalidate all sessions
- Confirm via email → notify user of password change
Authorization (Access Control)
Role-Based Access Control (RBAC)
User → has Role(s) → Role has Permission(s) → Permission grants Action on Resource
| Role |
Permissions |
viewer |
Read resources |
editor |
Read + create + update resources |
admin |
All operations + user management |
owner |
All operations + billing + delete |
Authorization rules
- Check permissions on every request — middleware, not ad-hoc
- Deny by default — if no permission is found, deny access
- Resource-level checks — user can edit their data, not all data
- Audit sensitive actions — log who did what, when
Authorization checklist per endpoint
1. Is the user authenticated? (401 if not)
2. Does their role include this permission? (403 if not)
3. Do they own/have access to this specific resource? (404 if not)
Return 404 (not 403) for resources the user shouldn't know exist.
Security Hardening
Rate limiting
- Login: 5 attempts per minute per IP/account
- Password reset: 3 requests per hour per email
- API: per-key limits based on plan
Account lockout
- Lock after 10 failed login attempts
- Require email verification to unlock
- Notify user of suspicious activity
Multi-factor authentication (MFA)
- Offer TOTP (authenticator app) as second factor
- Support recovery codes for lost authenticator
- Enforce MFA for admin/sensitive roles
Session security
- Regenerate session ID after privilege changes
- Invalidate all sessions on password change
- Show active sessions to users (allow revocation)
- Set reasonable idle timeout (30 min for sensitive apps)
Token Storage Guide
| Storage method |
Security |
Use case |
| HTTP-only Secure cookie |
✅ Best for web |
Sessions, access tokens |
| In-memory (JS variable) |
✅ Good for SPAs |
Short-lived access tokens |
| Secure OS keychain |
✅ Best for mobile |
Refresh tokens |
| localStorage |
❌ Avoid |
Vulnerable to XSS |
| URL parameters |
❌ Never |
Logged, cached, leaked |
PR Checklist for Auth Changes
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: authentication-43description: Guidelines for auth flows, session management, OAuth, JWT, and access control patterns Use when this capability is needed.4---56# Authentication Skill78## When to use this skill910Use when implementing login/signup, session management, OAuth integrations, role-based access control, or any security-sensitive auth feature.1112---1314## Auth Principles1516### 1. Never roll your own crypto17- Use established libraries for hashing, tokens, encryption18- Don't invent custom auth protocols19- Follow OWASP guidelines2021### 2. Defense in depth22- Auth at the API gateway / middleware (not per-endpoint)23- Validate tokens on every request24- Never trust the client2526### 3. Least privilege27- Users get minimum permissions needed28- Tokens scope to specific actions29- Admin access is audited3031---3233## Authentication Patterns3435### Pattern 1: Session-Based Auth36```37Client → POST /login (credentials) → Server creates session38Client → requests with session cookie → Server validates session39Client → POST /logout → Server destroys session40```4142**Best for:** Traditional web apps, server-rendered pages4344**Rules:**45- Store sessions server-side (database or Redis), not in cookies46- Use HTTP-only, Secure, SameSite cookies47- Set session expiry (24h default, configurable)48- Regenerate session ID after login (prevent session fixation)49- Invalidate session on logout and password change5051### Pattern 2: JWT (JSON Web Token)52```53Client → POST /login (credentials) → Server returns access + refresh tokens54Client → requests with Authorization: Bearer <access_token>55Client → POST /refresh (refresh_token) → Server returns new access token56```5758**Best for:** APIs, SPAs, mobile apps, microservices5960**Rules:**61- **Access tokens**: short-lived (15-30 minutes)62- **Refresh tokens**: longer-lived (7-30 days), stored securely63- Never store JWTs in localStorage (use HTTP-only cookies or memory)64- Include minimal claims (user ID, role — never sensitive data)65- Validate signature, expiry, and issuer on every request66- Support token revocation (blacklist or short-lived + rotation)6768### Pattern 3: OAuth 2.0 / OpenID Connect69```70Client → Redirect to provider → User authenticates → Redirect back with code71Server → Exchange code for tokens → Create local session/JWT72```7374**Best for:** "Login with Google/GitHub/etc.", third-party integrations7576**Rules:**77- Use Authorization Code Flow with PKCE (not Implicit Flow)78- Validate `state` parameter to prevent CSRF79- Validate ID token claims (issuer, audience, expiry)80- Store provider tokens securely if you need to call their APIs8182---8384## Password Handling8586### Rules87- **Hash passwords with bcrypt, scrypt, or Argon2** — never MD5/SHA88- **Salt automatically** (bcrypt does this) — never reuse salts89- **Minimum password length: 8 characters** — prefer 12+90- **Check against breached password lists** (Have I Been Pwned API)91- **Never log passwords** — not even hashed ones92- **Never send passwords in URLs** — always POST body93- **Never store plaintext passwords** — anywhere, ever9495### Password reset flow961. User requests reset → generate random token (not the password hash)972. Send token via email → link expires in 1 hour983. User clicks link → verify token, show new password form994. User sets new password → invalidate token, invalidate all sessions1005. Confirm via email → notify user of password change101102---103104## Authorization (Access Control)105106### Role-Based Access Control (RBAC)107```108User → has Role(s) → Role has Permission(s) → Permission grants Action on Resource109```110111| Role | Permissions |112|------|------------|113| `viewer` | Read resources |114| `editor` | Read + create + update resources |115| `admin` | All operations + user management |116| `owner` | All operations + billing + delete |117118### Authorization rules119- **Check permissions on every request** — middleware, not ad-hoc120- **Deny by default** — if no permission is found, deny access121- **Resource-level checks** — user can edit *their* data, not *all* data122- **Audit sensitive actions** — log who did what, when123124### Authorization checklist per endpoint125```1261. Is the user authenticated? (401 if not)1272. Does their role include this permission? (403 if not)1283. Do they own/have access to this specific resource? (404 if not)129```130131> Return 404 (not 403) for resources the user shouldn't know exist.132133---134135## Security Hardening136137### Rate limiting138- Login: 5 attempts per minute per IP/account139- Password reset: 3 requests per hour per email140- API: per-key limits based on plan141142### Account lockout143- Lock after 10 failed login attempts144- Require email verification to unlock145- Notify user of suspicious activity146147### Multi-factor authentication (MFA)148- Offer TOTP (authenticator app) as second factor149- Support recovery codes for lost authenticator150- Enforce MFA for admin/sensitive roles151152### Session security153- Regenerate session ID after privilege changes154- Invalidate all sessions on password change155- Show active sessions to users (allow revocation)156- Set reasonable idle timeout (30 min for sensitive apps)157158---159160## Token Storage Guide161162| Storage method | Security | Use case |163|---------------|----------|----------|164| HTTP-only Secure cookie | ✅ Best for web | Sessions, access tokens |165| In-memory (JS variable) | ✅ Good for SPAs | Short-lived access tokens |166| Secure OS keychain | ✅ Best for mobile | Refresh tokens |167| localStorage | ❌ Avoid | Vulnerable to XSS |168| URL parameters | ❌ Never | Logged, cached, leaked |169170---171172## PR Checklist for Auth Changes173174- [ ] Uses established auth library (no custom crypto)175- [ ] Passwords hashed with bcrypt/scrypt/Argon2176- [ ] Tokens are properly scoped and expire177- [ ] Access control checked at middleware level178- [ ] No sensitive data in logs, URLs, or error messages179- [ ] Rate limiting on auth endpoints180- [ ] Session invalidation on logout/password change181- [ ] Tests cover: valid login, invalid credentials, expired token, insufficient permissions182- [ ] Security review flagged for this PR183184---185> Converted and distributed by [TomeVault](https://tomevault.io/claim/xmenq) — claim your Tome and manage your conversions.186<!-- tomevault:4.0:skill_md:2026-04-14 -->