
JWT Authentication: Securing API Routes with JSON Web Tokens in FastAPI
What is JWT? A JSON Web Token (JWT) is a compact, self-contained token that proves who you are. Instead of sending your password with every request, you log in once, get a token, and use that token for all future requests. How It Works User sends email + password to /auth/login Server verifies credentials Server generates a JWT containing user ID User sends that JWT with every protected request Server verifies the token and grants access Generating the Token def create_token(user_id: int, email: str): payload = { "user_id": user_id, "email": email, "exp": datetime.utcnow() + timedelta(hours=24) } return jwt.encode(payload, SECRET_KEY, algorithm="HS256") The token contains user_id , email and an expiry time . It's signed with a secret key, tamper with it and it becomes invalid. Verifying the Token def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)): token = credentials.credentials try: payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) return paylo
Continue reading on Dev.to Python
Opens in a new tab


