| name | building-api-authentication |
| description | Build secure API authentication systems with OAuth2, JWT, API keys, and session management.
Use when implementing secure authentication flows.
Trigger with phrases like "build authentication", "add API auth", or "secure the API".
|
| allowed-tools | Read, Write, Edit, Grep, Glob, Bash(api:auth-*) |
| version | 1.23.0 |
| author | Jeremy Longshore <jeremy@intentsolutions.io> |
| license | MIT |
| tags | ["api","authentication","api-authentication"] |
| compatibility | Designed for Claude Code, also compatible with Codex and OpenClaw |
Building API Authentication
Overview
Build secure API authentication systems supporting JWT Bearer tokens, OAuth 2.0 authorization code and client credentials flows, API key management, and session-based authentication. Implement token issuance, validation, refresh rotation, revocation, and role-based access control (RBAC) with scoped permissions across all API endpoints.
Prerequisites
- Cryptographic library:
jsonwebtoken (Node.js), PyJWT (Python), or jjwt (Java)
- Secure secret storage: environment variables, AWS Secrets Manager, or HashiCorp Vault for JWT signing keys
- Database table for user credentials, refresh tokens, and API key storage
- Bcrypt or Argon2 for password hashing (never store plaintext passwords)
- OAuth 2.0 provider credentials for third-party auth integration (Google, GitHub, Auth0)
Instructions
- Examine existing authentication setup using Grep and Read, identifying current auth mechanisms, middleware placement, and any endpoints bypassing authentication.
- Implement JWT token issuance on successful login: sign with RS256 (asymmetric) or HS256 (symmetric), including
sub (user ID), iat, exp (15-minute access token), roles, and scopes in the payload.
- Create authentication middleware that extracts the Bearer token from the
Authorization header, verifies the signature and expiration, and injects the decoded user context into the request object.
- Implement refresh token rotation: issue a long-lived refresh token (30 days) alongside the access token, store a hash of the refresh token in the database, and rotate on each refresh (invalidating the previous token).
- Build role-based access control (RBAC) middleware that checks
user.roles against endpoint-required roles, supporting both role-level (admin, user) and scope-level (read:users, write:orders) authorization.
- Add API key authentication as an alternative to JWT for machine-to-machine communication: generate cryptographically random keys, store hashed values, and validate against the
X-API-Key header.
- Implement OAuth 2.0 client credentials flow for service-to-service authentication, with token caching and automatic renewal before expiration.
- Add brute-force protection on login endpoints: rate limit to 5 attempts per minute per IP, implement progressive lockout (15 min, 1 hour) after repeated failures, and log all authentication attempts.