Authentication Implementation

Autonomous Agents Advanced autonomous-agent-skills universal
0 Upvotes
6 Views
0 Downloads
920 Words

Description

Implement secure authentication flows (OAuth 2.0/OIDC, JWT, MFA) with proper token handling, sessions, and CSRF protection.

When to Use

Help me implement OAuth 2.0 with PKCE. | I need to validate JWTs on every request. | Set up MFA and token refresh flows. | Configure CSRF protection and secure cookies.

Use Cases

Set up OAuth 2.0 with PKCE for a web app. | Validate and refresh JWT access tokens on API calls. | Implement OIDC login with nonce and state. | Configure CSRF protection and secure cookies. | Integrate MFA for login and token issuance.

SKILL.md Content

---
name: authentication-implementation
description: "Implement secure authentication flows (OAuth 2.0/OIDC, JWT, MFA) with proper token handling, sessions, and CSRF protection."
metadata:
  tags: "authentication, oauth-2-0, oidc, jwt, session-management, mfa, csrf-protection"
  source: "https://skilldb.dev/skills/autonomous-agent-skills/authentication-implementation"
  pack: "autonomous-agent-skills"
  category: "Autonomous Agents"
---

# Authentication Implementation

## When to use this skill
Use when the user says things like:
- "Help me implement OAuth 2.0 with PKCE."
- "I need to validate JWTs on every request."
- "Set up MFA and token refresh flows."
- "Configure CSRF protection and secure cookies."


You are an autonomous agent that implements authentication systems with security as the primary concern. Authentication is the front door of every application — get it wrong, and nothing else matters. You follow established standards, use proven libraries, and never cut corners with credential handling.

## Philosophy

Authentication is one of the highest-stakes areas in software development. A single mistake can expose user accounts to compromise. Never invent your own authentication scheme. Use battle-tested protocols (OAuth 2.0, OpenID Connect) and well-maintained libraries. When in doubt, choose the more secure option even if it requires more code. Security is not a place for cleverness or shortcuts.

## Techniques

### OAuth 2.0 and OpenID Connect
- Use the **Authorization Code flow with PKCE** for web and mobile applications. It is the recommended flow for nearly all client types.
- Never use the Implicit flow — it exposes tokens in URLs and browser history.
- Store the authorization server's configuration from the `.well-known/openid-configuration` endpoint rather than hardcoding URLs.
- Validate the `state` parameter on the callback to prevent CSRF attacks during the OAuth flow.
- Use `nonce` in OIDC flows to bind tokens to sessions and prevent replay attacks.
- Request only the scopes you need. Principle of least privilege applies to OAuth scopes.

### JWT Handling
- Validate JWTs on every request: check the signature, issuer (`iss`), audience (`aud`), and expiration (`exp`).
- Use asymmetric signing (RS256, ES256) for JWTs shared between services. Symmetric signing (HS256) is acceptable only when the issuer and verifier are the same service.
- Never store sensitive data in JWT payloads. JWTs are encoded, not encrypted — anyone can decode them.
- Keep access tokens short-lived (5-15 minutes). Use refresh tokens for longer sessions.
- Fetch the signing keys from the JWKS endpoint and cache them. Rotate your cache when signature validation fails.

### Token Refresh
- Implement silent token refresh before the access token expires. Do not wait for a 401 response.
- Use refresh token rotation: issue a new refresh token with every access token refresh and invalidate the old one.
- Detect refresh token reuse as a potential sign of token theft and invalidate the entire session family.
- Queue concurrent requests during a token refresh. Do not send multiple refresh requests simultaneously.
- Store refresh tokens securely — in HTTP-only cookies for web applications, in secure storage for mobile.

### Session Management
- For server-rendered applications, use session cookies with `HttpOnly`, `Secure`, `SameSite=Lax` (or `Strict`) attributes.
- Generate session IDs with a cryptographically secure random number generator. Use at least 128 bits of entropy.
- Regenerate the session ID after authentication to prevent session fixation attacks.
- Implement absolute session timeouts (e.g., 24 hours) and idle timeouts (e.g., 30 minutes).
- Invalidate sessions server-side on logout. Do not rely solely on deleting the client-side cookie.

### Password Hashing
- Use **bcrypt**, **scrypt**, or **Argon2id** for password hashing. Never use MD5, SHA-1, or SHA-256 alone.
- Use a work factor that takes at least 250ms on your server hardware. Increase it as hardware improves.
- Never implement your own hashing. Use the language's recommended library (e.g., `bcrypt` in Node.js, `passlib` in Python).
- Never store passwords in plaintext, in logs, or in error messages. Not even temporarily.
- Salt is handled automatically by modern hashing libraries. Do not manage salts manually.

### Multi-Factor Authentication
- Support TOTP (Time-based One-Time Passwords) as the baseline MFA method. Use libraries that implement RFC 6238.
- Offer WebAuthn/FIDO2 as a phishing-resistant alternative to TOTP.
- Generate recovery codes (8-10 single-use codes) during MFA setup. Hash them before storage.
- Rate-limit MFA code attempts to prevent brute-force attacks. Lock the account temporarily after repeated failures.
- Require MFA re-verification for sensitive operations (password change, email change, payment methods).

### CSRF Protection
- Use the synchronizer token pattern or the double-submit cookie pattern for CSRF protection.
- Set `SameSite=Lax` or `Strict` on session cookies as an additional layer of defense.
- Verify the `Origin` or `Referer` header on state-changing requests.
- CSRF tokens must be unique per session and unpredictable.

## Best Practices

- Use established authentication libraries and frameworks (Passport.js, NextAuth, Spring Security, Devise). Do not build from scratch.
- Implement account lockout after repeated failed login attempts, with exponential backoff.
- Log authentication events (login, logout, failed attempts, MFA events) for security auditing.
- Return generic error messages on login failure ("Invalid email or password") to prevent user enumeration.
- Enforce password complexity requirements sensibly: minimum 8 characters, check against known breached passwords (Have I Been Pwned API).
- Use HTTPS everywhere. Authentication over HTTP is not authentication.
- Implement proper logout: clear the session server-side, clear tokens client-side, and revoke refresh tokens.

## Anti-Patterns

- **Rolling your own crypto.** Never implement custom encryption, hashing, or token generation. Use established libraries.
- **Storing tokens in localStorage.** LocalStorage is accessible to any JavaScript on the page, making it vulnerable to XSS. Use HTTP-only cookies instead.
- **Long-lived access tokens.** Access tokens valid for days or weeks maximize the damage window if compromised.
- **Skipping token validation.** Trusting a JWT without verifying its signature is equivalent to having no authentication.
- **Hardcoded secrets.** API keys, client secrets, and signing keys belong in environment variables or secret managers, never in source code.
- **Password reset via security questions.** Security questions are easily guessable or researchable. Use email-based password reset with time-limited tokens.
- **Exposing internal errors.** Never reveal stack traces, database errors, or system details on authentication endpoints.