Can you help me design the JWT auth middleware for our API gateway?
AI
AIMI Assistantthinking...
AI
AIMI AssistantGPT-4ojust now
Sure! I'll help you design a robust JWT authentication middleware. Let me start by understanding your requirements.Key components I recommend:
Would you like me to elaborate on any specific part?
1.Token verification — Verify RS256 signatures using your public key from Vault
2.Refresh token rotation — Issue new refresh tokens on each use, invalidating the old one
3.Blacklist — Store revoked tokens in Redis with TTL matching token expiry
4.Rate limiting — 5 req/min per IP on refresh endpoint
typescript
// middleware/auth.ts
import { verify, type JwtPayload } from 'jsonwebtoken'
import { redis } from '../lib/redis'interface AuthOptions {
requireAuth: boolean
roles?: string[]
}export async function authMiddleware(req: Request, opts: AuthOptions) {
const token = extractToken(req.headers)
if (!token && opts.requireAuth) {
return Response.json({ error: 'Missing token' }, { status: 401 })
}
// ... verification logic
}AI
AIMI Assistantjust now
AI
AIMI AssistantClaude 42m ago
Tests passed! Here's a summary of what was verified:
•Valid token: 200 OK
•Expired token: 401 Unauthorized
•Malformed token: 401 Unauthorized
•Missing token: 401 Unauthorized (when required)
•Revoked token: 401 Unauthorized
•Rate limit exceeded: 429 Too Many Requests
All 24 test cases green. Ready for PR.Great work! Could you also add WebSocket support?
AI
AIMI Assistantthinking...
AI
AIMI AssistantGPT-4o1m ago
Added WebSocket support. The middleware now handles both HTTP and WebSocket connections:Tokens are passed via query param
typescript
// For WebSocket upgrade
if (req.headers.get('upgrade') === 'websocket') {
const token = new URL(req.url).searchParams.get('token')
if (!token) return new Response(null, { status: 401 })
// verify token...
}?token= for WebSocket connections. The same verification and blacklist logic applies.