Challenge - 5 Problems
JWT Verification Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this FastAPI JWT verification snippet?
Consider this FastAPI endpoint that verifies a JWT token passed in the Authorization header. What will be the response if the token is expired?
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials import jwt app = FastAPI() security = HTTPBearer() SECRET_KEY = "mysecret" async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)): try: payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=["HS256"]) return payload except jwt.ExpiredSignatureError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired") @app.get("/protected") async def protected_route(payload=Depends(verify_token)): return {"user": payload["sub"]}
Attempts:
2 left
💡 Hint
Think about what happens when jwt.decode raises ExpiredSignatureError.
✗ Incorrect
The code catches jwt.ExpiredSignatureError and raises HTTPException with 401 status and 'Token expired' detail. So the response is a 401 error with that message.
📝 Syntax
intermediate1:30remaining
Which option correctly decodes a JWT token in FastAPI?
You want to decode a JWT token string using PyJWT in FastAPI. Which code snippet correctly decodes the token with the HS256 algorithm and a secret key?
Attempts:
2 left
💡 Hint
Check the PyJWT decode function signature for required parameters.
✗ Incorrect
PyJWT's decode requires the token, the secret key, and algorithms list as parameters. Option A matches this signature correctly.
🔧 Debug
advanced2:30remaining
Why does this FastAPI JWT verification code raise a 500 error instead of 401?
Given this code snippet, why does the server return a 500 Internal Server Error instead of a 401 Unauthorized when the token is invalid?
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials import jwt app = FastAPI() security = HTTPBearer() SECRET_KEY = "secret" async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)): try: payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=["HS256"]) return payload except jwt.InvalidTokenError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") @app.get("/secure") async def secure_route(payload=Depends(verify_token)): return {"user": payload["sub"]}
Attempts:
2 left
💡 Hint
Consider which exceptions jwt.decode can raise and which are caught.
✗ Incorrect
jwt.decode can raise ExpiredSignatureError which is not a subclass of InvalidTokenError, so it is uncaught and causes a 500 error. Catching ExpiredSignatureError separately fixes this.
❓ state_output
advanced2:00remaining
What is the value of 'user' returned by this FastAPI JWT endpoint?
Given this JWT payload and FastAPI endpoint, what will be the value of 'user' in the JSON response?
FastAPI
import jwt from fastapi import FastAPI, Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials app = FastAPI() security = HTTPBearer() SECRET_KEY = "key" # JWT token payload example: {"sub": "alice", "role": "admin"} async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)): payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=["HS256"]) return payload @app.get("/user") async def get_user(payload=Depends(verify_token)): return {"user": payload.get("sub", "anonymous")}
Attempts:
2 left
💡 Hint
Look at how the 'sub' field is accessed in the payload.
✗ Incorrect
The code returns payload.get("sub", "anonymous"), so if 'sub' exists it returns its value. The example payload has 'sub': 'alice', so 'alice' is returned.
🧠 Conceptual
expert3:00remaining
Which statement best explains JWT token verification in FastAPI?
Select the option that correctly describes how JWT token verification should be implemented in a FastAPI app to ensure secure access to protected routes.
Attempts:
2 left
💡 Hint
Think about best practices for secure token verification in FastAPI.
✗ Incorrect
Option B describes the correct approach: use FastAPI dependencies to extract and verify tokens securely, handle errors properly, and provide payload data to routes.