0
0
FastAPIframework~10 mins

JWT token verification in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
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.