Bird
Raised Fist0
FastAPIframework~10 mins

JWT token verification in FastAPI - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to decode a JWT token using the secret key.

FastAPI
from jose import jwt

def verify_token(token: str, secret_key: str):
    payload = jwt.[1](token, secret_key, algorithms=["HS256"])
    return payload
Drag options to blanks, or click blank then click option'
Averify
Bencode
Cdecode
Dsign
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'encode' instead of 'decode' will cause an error because encoding creates tokens, not verifies them.
Using 'sign' or 'verify' are not valid methods in the jose.jwt module.
2fill in blank
medium

Complete the code to raise an exception if the token is invalid.

FastAPI
from jose import JWTError

def verify_token(token: str, secret_key: str):
    try:
        payload = jwt.decode(token, secret_key, algorithms=["HS256"])
    except [1]:
        raise ValueError("Invalid token")
    return payload
Drag options to blanks, or click blank then click option'
ATypeError
BValueError
CKeyError
DJWTError
Attempts:
3 left
💡 Hint
Common Mistakes
Catching ValueError will not catch JWT decode errors specifically.
KeyError and TypeError are unrelated to JWT token verification.
3fill in blank
hard

Fix the error in the code to correctly extract the user ID from the token payload.

FastAPI
def get_user_id(token: str, secret_key: str):
    payload = jwt.decode(token, secret_key, algorithms=["HS256"])
    user_id = payload.get([1])
    if user_id is None:
        raise ValueError("User ID not found in token")
    return user_id
Drag options to blanks, or click blank then click option'
A"sub"
B"user"
C"id"
D"uid"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'user', 'id', or 'uid' keys may not match the token payload structure.
Not checking if the user ID exists can cause errors later.
4fill in blank
hard

Fill both blanks to create a FastAPI dependency that verifies the JWT token from the Authorization header.

FastAPI
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user(token: str = Depends([1])):
    try:
        payload = jwt.decode(token, [2], algorithms=["HS256"])
    except JWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return payload
Drag options to blanks, or click blank then click option'
Aoauth2_scheme
BDepends
C"secret"
Dsecret_key
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Depends' instead of the OAuth2 scheme instance will cause errors.
Using a string 'secret' instead of the secret_key variable will fail token decoding.
5fill in blank
hard

Fill all three blanks to create a function that verifies the JWT token and returns the user email if valid.

FastAPI
def get_user_email(token: str, secret_key: str):
    try:
        payload = jwt.decode(token, [1], algorithms=["HS256"])
        email = payload.get([2])
        if email is None:
            raise ValueError("Email not found in token")
    except JWTError:
        raise ValueError("Invalid token")
    return [3]
Drag options to blanks, or click blank then click option'
Asecret_key
B"email"
Cemail
D"sub"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys like 'sub' instead of 'email' will cause missing data.
Returning the wrong variable or string instead of the email variable.

Practice

(1/5)
1. What is the main purpose of JWT token verification in a FastAPI application?
easy
A. To check if the user token is valid and trusted
B. To encrypt the user's password
C. To store user data in the database
D. To generate HTML pages dynamically

Solution

  1. Step 1: Understand JWT token role

    JWT tokens are used to prove a user's identity securely.
  2. Step 2: Identify verification purpose

    Verification checks if the token is valid and trusted before allowing access.
  3. Final Answer:

    To check if the user token is valid and trusted -> Option A
  4. Quick 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
A. Depends()
B. Form()
C. RequestBody()
D. OAuth2PasswordBearer

Solution

  1. Step 1: Identify FastAPI dependency for JWT

    OAuth2PasswordBearer is designed to extract bearer tokens from headers.
  2. Step 2: Confirm usage for JWT verification

    This dependency helps get the token string to verify it in your code.
  3. Final Answer:

    OAuth2PasswordBearer -> Option D
  4. Quick 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 payload
medium
A. The function returns the payload even if token is invalid
B. The server crashes with an unhandled exception
C. An HTTP 401 error is raised with 'Invalid token' message
D. The token is ignored and user is treated as anonymous

Solution

  1. Step 1: Analyze try-except block

    If jwt.decode fails, it raises JWTError which is caught by except.
  2. Step 2: Check except block behavior

    It raises HTTPException with status 401 and message 'Invalid token'.
  3. Final Answer:

    An HTTP 401 error is raised with 'Invalid token' message -> Option C
  4. Quick 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 payload
medium
A. HTTPException is raised but not returned or raised properly
B. Missing import for HTTPException
C. jwt.decode is called with wrong parameters
D. The function should not return payload

Solution

  1. Step 1: Check exception handling

    HTTPException is created but not raised or returned, so error is ignored.
  2. Step 2: Correct usage of HTTPException

    Must use 'raise HTTPException(...)' to properly stop execution and send error.
  3. Final Answer:

    HTTPException is raised but not returned or raised properly -> Option A
  4. Quick 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
A. Check the token manually inside the route function without dependencies
B. Use a dependency that verifies the JWT token and include it in the route
C. Add a middleware that ignores JWT tokens
D. Use a global variable to store token validity

Solution

  1. Step 1: Understand FastAPI dependencies

    Dependencies can run code before route logic and reject invalid requests.
  2. Step 2: Use dependency to verify JWT

    Including a JWT verification dependency ensures only valid tokens allow access.
  3. Final Answer:

    Use a dependency that verifies the JWT token and include it in the route -> Option B
  4. Quick 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