Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)
JWT Authentication with Refresh Token Rotation:
In Simple Words: Issue a short-lived Access Token (15m) and a long-lived Refresh Token (7d). On refresh, invalidate the old refresh token and issue a brand new pair.
python
import jwt
from datetime import datetime, timedelta, timezone
SECRET_KEY = "my_jwt_secret"
def create_access_token(user_id: str) -> str:
payload = {
"sub": user_id,
"exp": datetime.now(timezone.utc) + timedelta(minutes=15)
}
return jwt.encode(payload, SECRET_KEY, algorithm="HS256")