🔒

JWT Authentication Implementation

Implement secure JWT-based authentication with refresh tokens

Intermediate🔒 SecurityAll Models
prompt template
Implement JWT authentication for:

**Stack:** [STACK — e.g., "Next.js API routes + PostgreSQL"]
**User model:** [FIELDS — e.g., "email, password, role, organization_id"]

Generate:
1. **Token pair** — short-lived access token (15min) + long-lived refresh token (7d)
2. **Login flow** — validate credentials, issue token pair, set httpOnly cookies
3. **Token refresh** — silent refresh before access token expires
4. **Logout** — invalidate refresh token, clear cookies
5. **Middleware** — verify token, attach user to request context
6. **Password hashing** — bcrypt with proper salt rounds
7. **Security headers** — CSRF protection, SameSite cookies, Secure flag
8. **Token rotation** — new refresh token on each refresh (detect token reuse)

Security requirements:
- Never store tokens in localStorage
- Refresh tokens stored in DB for revocation
- Rate limit login attempts
- Constant-time password comparison

Include all route handlers, middleware, and database schema.

How to Use This Prompt

  1. 1Copy the prompt template above
  2. 2Paste into Claude, ChatGPT, or Cursor
  3. 3Replace [bracketed placeholders] with your specific project details
  4. 4Iterate on the AI output to refine and customize the results