12 min readNgusa
Implementing Secure JWT Authentication in Backend APIs
Authentication is critical for any backend application. Here's how to implement secure JWT-based authentication with best practices.
JWT Authentication Flow
- User logs in with credentials
- Server validates and returns JWT access token + refresh token
- Client includes token in subsequent requests
- Server validates token and processes request
Implementation with FastAPI
Password Hashing
python
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)Token Generation
python
from jose import jwt
from datetime import datetime, timedelta
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")
def create_refresh_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(days=7)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")Protected Routes
python
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer
security = HTTPBearer()
async def get_current_user(token: str = Depends(security)):
try:
payload = jwt.decode(token.credentials, SECRET_KEY)
return payload
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")Security Best Practices
- Short-lived Access Tokens - 15-30 minutes maximum
- HTTP-only Cookies - Store tokens securely
- HTTPS Only - Never transmit tokens over HTTP
- Token Rotation - Refresh tokens regularly
- Blacklisting - Implement token revocation
Refresh Token Strategy
Store refresh tokens in database with:
- User association
- Expiration date
- Device/IP information
- Revocation status
Conclusion
Proper JWT implementation with refresh tokens, password hashing, and security best practices is essential for building secure backend APIs.