Understanding JWT Authentication
JSON Web Tokens (JWT) provide a stateless authentication mechanism perfect for modern APIs. Let's implement secure JWT authentication in FastAPI.
Setting Up Dependencies
pip install python-jose[cryptography] passlib[bcrypt] python-multipart
Creating JWT Tokens
Implement token creation with proper expiration:
from jose import jwt
from datetime import datetime, timedelta
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=30)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")
Refresh Token Strategy
Implement refresh tokens for better security:
- Short-lived access tokens (15-30 minutes)
- Long-lived refresh tokens (7-30 days)
- Token rotation on refresh
- Secure storage in httpOnly cookies
Security Best Practices
- Use strong secret keys (32+ characters)
- Implement token blacklisting for logout
- Add rate limiting to prevent brute force
- Use HTTPS in production
- Validate token signatures properly