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.
JWT token verification in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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}
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!"}
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.
Practice
1. What is the main purpose of JWT token verification in a FastAPI application?
easy
Solution
Step 1: Understand JWT token role
JWT tokens are used to prove a user's identity securely.Step 2: Identify verification purpose
Verification checks if the token is valid and trusted before allowing access.Final Answer:
To check if the user token is valid and trusted -> Option AQuick Check:
JWT verification = check token validity [OK]
Hint: JWT verification means confirming token is valid [OK]
Common Mistakes:
- Confusing verification with encryption
- Thinking JWT stores user data permanently
- Mixing token verification with UI rendering
2. Which FastAPI dependency is commonly used to extract and verify a JWT token from the request header?
easy
Solution
Step 1: Identify FastAPI dependency for JWT
OAuth2PasswordBearer is designed to extract bearer tokens from headers.Step 2: Confirm usage for JWT verification
This dependency helps get the token string to verify it in your code.Final Answer:
OAuth2PasswordBearer -> Option DQuick Check:
OAuth2PasswordBearer extracts JWT token [OK]
Hint: OAuth2PasswordBearer extracts token from header [OK]
Common Mistakes:
- Using Depends() alone without OAuth2PasswordBearer
- Confusing Form() with header token extraction
- Using RequestBody() which reads body, not headers
3. Given this FastAPI code snippet, what will happen if the JWT token is invalid?
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
return payloadmedium
Solution
Step 1: Analyze try-except block
If jwt.decode fails, it raises JWTError which is caught by except.Step 2: Check except block behavior
It raises HTTPException with status 401 and message 'Invalid token'.Final Answer:
An HTTP 401 error is raised with 'Invalid token' message -> Option CQuick Check:
Invalid token triggers HTTP 401 error [OK]
Hint: Invalid JWT triggers HTTPException 401 [OK]
Common Mistakes:
- Assuming function returns payload on invalid token
- Thinking server crashes without handling error
- Believing token is ignored silently
4. Identify the error in this FastAPI JWT verification code:
from fastapi import Depends, HTTPException
from jose import jwt, JWTError
def verify_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except:
HTTPException(status_code=401, detail="Invalid token")
return payloadmedium
Solution
Step 1: Check exception handling
HTTPException is created but not raised or returned, so error is ignored.Step 2: Correct usage of HTTPException
Must use 'raise HTTPException(...)' to properly stop execution and send error.Final Answer:
HTTPException is raised but not returned or raised properly -> Option AQuick Check:
Use 'raise' keyword with HTTPException [OK]
Hint: Always 'raise' HTTPException to trigger error [OK]
Common Mistakes:
- Forgetting 'raise' before HTTPException
- Catching too broad exceptions without logging
- Returning payload even on error
5. How can you protect a FastAPI route so that only requests with a valid JWT token can access it?
hard
Solution
Step 1: Understand FastAPI dependencies
Dependencies can run code before route logic and reject invalid requests.Step 2: Use dependency to verify JWT
Including a JWT verification dependency ensures only valid tokens allow access.Final Answer:
Use a dependency that verifies the JWT token and include it in the route -> Option BQuick Check:
Dependency verifies JWT before route runs [OK]
Hint: Protect routes with JWT verification dependency [OK]
Common Mistakes:
- Checking token inside route instead of dependency
- Ignoring token verification in middleware
- Using global variables for token state
