Bird
0
0

You want to create a FastAPI dependency that verifies a JWT token and extracts the username. Which code snippet correctly implements this?

hard🚀 Application Q8 of 15
FastAPI - Authentication and Security
You want to create a FastAPI dependency that verifies a JWT token and extracts the username. Which code snippet correctly implements this?
Aasync def get_username(token: str = Depends(oauth2_scheme)): payload = jwt.decode(token, "secret", algorithms=["HS256"]) return payload.get("sub")
Basync def get_username(token: str): return token.split('.')[0]
Cdef get_username(token: str = Depends(oauth2_scheme)): return token
Dasync def get_username(): return "user"
Step-by-Step Solution
Solution:
  1. Step 1: Decode JWT token properly

    Use jwt.decode with secret and algorithm to get payload.
  2. Step 2: Extract username from payload

    Username is usually in 'sub' claim, accessed via payload.get("sub").
  3. Final Answer:

    Async function decoding token and returning payload 'sub' -> Option A
  4. Quick Check:

    Decode JWT and get 'sub' claim for username [OK]
Quick Trick: Decode JWT and get 'sub' claim for username [OK]
Common Mistakes:
MISTAKES
  • Splitting token string instead of decoding
  • Not using Depends for token injection
  • Returning token string instead of username

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes