JWT token verification helps check if a user is allowed to access certain parts of an app. It keeps the app safe by confirming the user's identity.
0
0
JWT token verification in FastAPI
Introduction
When you want to protect API routes so only logged-in users can use them.
When you need to check if a user's token is still valid before giving access.
When building apps that require user login and secure data exchange.
When you want to avoid asking users to log in repeatedly by trusting their token.
When you want to confirm the token was created by your app and not changed.
Syntax
FastAPI
from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") SECRET_KEY = "your-secret-key" ALGORITHM = "HS256" async def verify_token(token: str = Depends(oauth2_scheme)): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id: str = payload.get("sub") if user_id is None: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") return user_id except JWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
The Depends function helps FastAPI get the token automatically from the request.
The jwt.decode checks the token using your secret key and algorithm.
Examples
This example shows how to protect a route so only users with a valid token can access it.
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() @app.get("/users/me") async def read_users_me(user_id: str = Depends(verify_token)): return {"user_id": user_id}
This shows how to decode a JWT token manually outside FastAPI dependencies.
FastAPI
from jose import jwt # Decode token manually payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id = payload.get("sub")
Sample Program
This FastAPI app has a protected route at /protected. It uses JWT token verification to allow access only if the token is valid and contains a user ID.
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt app = FastAPI() SECRET_KEY = "mysecretkey123" ALGORITHM = "HS256" oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def verify_token(token: str = Depends(oauth2_scheme)): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id: str = payload.get("sub") if user_id is None: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") return user_id except JWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") @app.get("/protected") async def protected_route(user_id: str = Depends(verify_token)): return {"message": f"Hello user {user_id}, you are authorized!"}
OutputSuccess
Important Notes
Always keep your SECRET_KEY private and never share it.
Tokens usually have an expiration time; verify it if needed.
Use HTTPS to keep tokens safe during transmission.
Summary
JWT token verification checks if a user token is valid and trusted.
FastAPI uses dependencies to get and verify tokens easily.
Protect routes by requiring a valid token before access.