Comprehensive JWT authentication expert for senior developers (10+ years experience)...
Comprehensive senior-level JWT authentication assistant that intelligently detects your project stack and implements production-ready, secure authentication systems.
Complete Auth System
Security Implementation
Advanced Features
Framework Support
When triggered, automatically execute:
# Detect language and framework
view package.json # Node.js project
view requirements.txt # Python project
view pyproject.toml # Python with modern tools
view next.config.js # Next.js
view tsconfig.json # TypeScript
# Scan existing auth
view src/
view app/
view routes/
view middleware/
view models/
Based on detected files:
Check for:
Generate based on stack:
{
"sub": "user_id", // Subject (user identifier)
"email": "user@example.com",
"role": "admin", // For RBAC
"permissions": ["read", "write"],
"iat": 1234567890, // Issued at
"exp": 1234568790, // Expires (15 min from iat)
"jti": "unique_token_id" // JWT ID for blacklisting
}
{
"sub": "user_id",
"type": "refresh",
"tokenFamily": "family_id", // For rotation detection
"iat": 1234567890,
"exp": 1235172690 // 7 days
}
// ā NEVER DO THIS - Vulnerable to XSS
localStorage.setItem('token', token)
// ā
CORRECT - HTTP-only cookie
res.cookie('accessToken', token, {
httpOnly: true, // Not accessible via JavaScript
secure: true, // HTTPS only
sameSite: 'strict', // CSRF protection
maxAge: 15 * 60 * 1000 // 15 minutes
})
res.cookie('refreshToken', refreshToken, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
path: '/api/auth/refresh' // Only sent to refresh endpoint
})
import bcrypt from 'bcrypt'
// Hash on registration
const hashedPassword = await bcrypt.hash(password, 12) // 12 rounds minimum
// Verify on login
const isValid = await bcrypt.compare(password, user.hashedPassword)
1. Client request with expired access token
2. Server detects expiration ā Check refresh token
3. Validate refresh token
4. Generate NEW access token + NEW refresh token (rotation)
5. Invalidate old refresh token (prevent reuse)
6. Set new tokens in HTTP-only cookies
7. Return success to client
// Store invalidated tokens in Redis/database
await redis.set(`blacklist:${tokenId}`, 'true', 'EX', tokenExpiry)
// Check on every request
const isBlacklisted = await redis.get(`blacklist:${tokenId}`)
if (isBlacklisted) {
throw new UnauthorizedError('Token has been revoked')
}
1. Registration
POST /api/auth/register
{
"email": "user@example.com",
"password": "SecurePass123!",
"name": "John Doe"
}
ā Hash password (bcrypt)
ā Create user in database
ā Generate email verification token
ā Send verification email
ā Return success (NO tokens yet)
2. Email Verification
GET /api/auth/verify-email?token=verification_token
ā Verify token validity
ā Mark email as verified
ā Allow user to login
3. Login
POST /api/auth/login
{
"email": "user@example.com",
"password": "SecurePass123!"
}
ā Validate credentials
ā Check email verified
ā Generate access token (15min)
ā Generate refresh token (7 days)
ā Store refresh token in database
ā Set HTTP-only cookies
ā Return user info (NO tokens in body)
4. Access Protected Route
GET /api/users/profile
Cookie: accessToken=xxx; refreshToken=yyy
ā Extract token from cookie
ā Verify token signature
ā Check expiration
ā Check blacklist
ā Attach user to request
ā Continue to route handler
5. Token Refresh (When Access Token Expires)
POST /api/auth/refresh
Cookie: refreshToken=xxx
ā Extract refresh token from cookie
ā Verify refresh token
ā Check if revoked/blacklisted
ā Generate NEW access token
ā Generate NEW refresh token (rotation)
ā Invalidate old refresh token
ā Set new cookies
ā Return success
6. Logout
POST /api/auth/logout
Cookie: accessToken=xxx; refreshToken=yyy
ā Extract tokens
ā Blacklist access token
ā Delete refresh token from database
ā Clear cookies
ā Return success
For framework-specific implementations, load:
Critical (Auto-Fix Immediately)
High Priority (Propose & Fix)
Medium Priority (Recommend)
// Middleware-based with cookie-parser
app.use(cookieParser())
app.use('/api/protected', authenticateToken)
// Token in HTTP-only cookie
res.cookie('accessToken', token, cookieOptions)
// Middleware for route protection
export function middleware(request: NextRequest) {
const token = request.cookies.get('accessToken')
// Verify and protect routes
}
// API routes with cookies
import { cookies } from 'next/headers'
cookies().set('accessToken', token, cookieOptions)
# Dependency injection
async def get_current_user(token: str = Cookie(...)):
# Verify token from cookie
return user
@app.get("/protected")
async def protected_route(user = Depends(get_current_user)):
return {"user": user}
Complete Auth System: "Create a complete JWT auth system for Express with refresh tokens in cookies"
Add to Existing: "Add JWT authentication to my Next.js app"
Security Audit: "Audit my JWT implementation for security vulnerabilities"
Protected Routes: "Implement JWT middleware for protected routes"
RBAC: "Add role-based access control to my auth system"
Frontend: "Implement JWT auth in React with protected routes"