Secure JWT Implementation with AI Prompts

Share

TL;DR

JWTs are easy to implement wrong. Use RS256 or ES256 (not HS256 with weak secrets), validate all claims, set short expiration times, and implement proper refresh token rotation. These prompts help you avoid the common JWT security pitfalls.

Secure Token Generation

Generate Secure JWTs

Create secure JWT generation for my authentication system.

Language: TypeScript/JavaScript/Python

Requirements:

  1. Use RS256 or ES256 algorithm (asymmetric)
  2. Short expiration time (15 minutes for access token)
  3. Include required claims: iss, sub, aud, exp, iat, jti
  4. Minimal payload (don't store sensitive data)

Token payload should include:

  • sub: user ID
  • iss: your domain
  • aud: intended audience
  • exp: expiration timestamp
  • iat: issued at timestamp
  • jti: unique token ID (for revocation)
  • role: user role (if needed)

Create:

  • generateAccessToken(userId, role)
  • generateRefreshToken(userId)
  • Key pair generation script
  • Key rotation strategy

Secure Token Validation

Validate JWTs Properly

Implement secure JWT validation that prevents common attacks.

Validation must:

  1. Explicitly specify allowed algorithms (prevent algorithm confusion)
  2. Verify signature with correct key
  3. Check exp claim (reject expired tokens)
  4. Check iat claim (reject future-dated tokens)
  5. Verify iss matches expected issuer
  6. Verify aud matches expected audience
  7. Check jti against revocation list (if implementing revocation)

Reject tokens that:

  • Use 'none' algorithm
  • Use unexpected algorithm
  • Have missing required claims
  • Are expired or not yet valid
  • Don't match expected issuer/audience

Return clear error types:

  • TokenExpiredError
  • InvalidSignatureError
  • InvalidClaimsError

Never trust the algorithm from the token header: Always specify which algorithms you accept. Attackers can change the algorithm to 'none' or switch from RS256 to HS256 using your public key as the secret.

Refresh Token Rotation

Implement Token Refresh

Implement secure refresh token rotation.

Flow:

  1. On login, issue access token (15 min) + refresh token (7 days)
  2. Store refresh token hash in database with user ID
  3. When access token expires, client sends refresh token
  4. Validate refresh token, issue new access + new refresh token
  5. Invalidate old refresh token (rotation)

Security measures:

  • Refresh tokens are single-use (rotate on each use)
  • Detect token reuse (indicates theft)
  • Store refresh token family for revocation
  • If reuse detected, invalidate entire family
  • Bind refresh token to device/fingerprint

Implement:

  • refreshTokens(refreshToken) -> { accessToken, refreshToken }
  • revokeRefreshToken(tokenId)
  • revokeAllUserTokens(userId)

Token Revocation

JWT Revocation Strategy

Add revocation capability to my JWT system.

Challenge: JWTs are stateless, but we need to revoke them.

Options:

  1. Short expiration + refresh tokens (recommended)
  2. Token blacklist in Redis
  3. Version number in user record

Implement hybrid approach:

  • Access tokens: 15 min, no revocation check (short-lived)
  • Refresh tokens: stored in DB, can be revoked
  • On logout: delete refresh token
  • On password change: invalidate all refresh tokens

For immediate revocation needs:

  • Store jti in Redis with TTL matching token expiration
  • Check blacklist only for sensitive operations
  • Background cleanup of expired entries

Pro tip: Consider using a library like jose (JavaScript) or PyJWT (Python) with careful configuration. Don't implement JWT signing/verification yourself.

HS256 or RS256?

RS256 (asymmetric) is generally more secure because the public key can be shared without compromising signing ability. HS256 requires sharing the secret with anyone who needs to verify tokens, increasing risk.

Where should I store JWTs on the client?

Memory is safest (cleared on page refresh). HttpOnly cookies work for web apps. localStorage is convenient but vulnerable to XSS. Never store in sessionStorage or plain cookies.

Check Your JWT Security

Scan your JWT implementation for common vulnerabilities.

Start Free Scan
AI Fix Prompts

Secure JWT Implementation with AI Prompts