Complete the code to decode a JWT token using the secret key.
from jose import jwt def verify_token(token: str, secret_key: str): payload = jwt.[1](token, secret_key, algorithms=["HS256"]) return payload
The jwt.decode function is used to decode and verify the JWT token using the secret key.
Complete the code to raise an exception if the token is invalid.
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
The JWTError exception is raised by the jwt.decode function when the token is invalid or expired.
Fix the error in the code to correctly extract the user ID from the token payload.
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
The standard JWT claim for the subject (user identifier) is "sub". This key holds the user ID in the token payload.
Fill both blanks to create a FastAPI dependency that verifies the JWT token from the Authorization header.
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
The oauth2_scheme dependency extracts the token from the Authorization header. The secret_key is used to decode the token.
Fill all three blanks to create a function that verifies the JWT token and returns the user email if valid.
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]
The function uses secret_key to decode the token, looks for the "email" key in the payload, and returns the email variable.