0
0
FastAPIframework~20 mins

JWT token verification in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JWT Verification Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2: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"]}
A{"detail": "Token expired"} with status 401
B{"user": "sub"} with status 200
C500 Internal Server Error
D{"detail": "Invalid token"} with status 401
Attempts:
2 left
💡 Hint
Think about what happens when jwt.decode raises ExpiredSignatureError.
📝 Syntax
intermediate
1: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?
Apayload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
Bpayload = jwt.decode(token, algorithms=["HS256"], key=SECRET_KEY)
Cpayload = jwt.decode(token, SECRET_KEY)
Dpayload = jwt.decode(token, key=SECRET_KEY)
Attempts:
2 left
💡 Hint
Check the PyJWT decode function signature for required parameters.
🔧 Debug
advanced
2: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"]}
ABecause the SECRET_KEY is incorrect, causing decode to fail silently
BBecause the HTTPBearer dependency raises an exception before verify_token runs
CBecause jwt.InvalidTokenError is not the base exception for all JWT errors, some errors are uncaught causing 500
DBecause the code does not catch jwt.ExpiredSignatureError separately, causing unhandled exceptions
Attempts:
2 left
💡 Hint
Consider which exceptions jwt.decode can raise and which are caught.
state_output
advanced
2: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")}
ANone
B"admin"
C"alice"
D"anonymous"
Attempts:
2 left
💡 Hint
Look at how the 'sub' field is accessed in the payload.
🧠 Conceptual
expert
3: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.
ADecode the JWT token on the client side and send the decoded payload to the server to avoid server-side verification.
BUse a dependency that extracts the token from the Authorization header, decodes it with a secret key and algorithm, handles exceptions for expired or invalid tokens, and returns the payload for route use.
CStore the JWT token in a global variable and check it manually in each route handler without using dependencies.
DSkip token verification and rely on HTTPS encryption to secure the API endpoints.
Attempts:
2 left
💡 Hint
Think about best practices for secure token verification in FastAPI.