Secure JWT Authentication

security
TypeScript
architecture
strict_senior
Remix

Production-ready JWT auth with refresh tokens, secure cookies, and proper validation.

12/8/2025

Prompt

Secure JWT Authentication

Implement production-ready JWT authentication for a [Framework] API.

Token Strategy

Access Tokens

  • Lifetime: Short-lived (15 minutes)
  • Contains user claims
  • Used for API authentication

Refresh Tokens

  • Lifetime: Long-lived (7 days)
  • Used to obtain new access tokens
  • Stored securely

Security Implementation

Secure Token Storage

  • Store refresh token in httpOnly cookies
  • Set secure flag (HTTPS only)
  • Set sameSite attribute (CSRF protection)

Token Generation

  • JWT Claims:
    • sub - Subject (user ID)
    • exp - Expiration time
    • iat - Issued at
    • roles - User roles/permissions
  • Strong secret key
  • Use HS256 or RS256 algorithm

Token Verification

  • Verify signature
  • Check expiration
  • Validate claims
  • Middleware for protected routes

Refresh Token Rotation

  • Invalidate old token on refresh
  • Issue new refresh token
  • Prevent token reuse attacks

Token Revocation

  • Blacklist/revocation strategy
  • Database or Redis for tracking
  • Logout invalidates tokens

Additional Security

CSRF Protection

  • Double-submit cookie pattern
  • CSRF tokens for state-changing operations
  • SameSite cookie attribute

Rate Limiting

  • Limit login attempts
  • Prevent brute force attacks
  • Per-IP and per-user rate limits

Password Security

  • bcrypt hashing (cost factor 12)
  • Salt automatically included
  • Never store plain text passwords

Input Validation

  • Validate all user inputs
  • Sanitize data
  • Prevent injection attacks

API Endpoints

Implement the following:

POST /auth/login

  • Validate credentials
  • Generate access + refresh tokens
  • Set httpOnly cookie
  • Return access token in response

POST /auth/refresh

  • Verify refresh token
  • Generate new access token
  • Rotate refresh token
  • Return new tokens

POST /auth/logout

  • Invalidate tokens
  • Clear cookies
  • Add to blacklist

Requirements

  • Production-ready implementation
  • Comprehensive security measures
  • Well-documented code
  • Error handling

Tags

jwt
authentication
security
tokens

Tested Models

gpt-4
claude-3-opus

Comments (0)

Sign in to leave a comment

Sign In