Bird
0
0

You want to protect a FastAPI route so only requests with the exact Bearer token "secret123" are allowed. Which code snippet correctly implements this?

hard🚀 Application Q15 of 15
FastAPI - Authentication and Security
You want to protect a FastAPI route so only requests with the exact Bearer token "secret123" are allowed. Which code snippet correctly implements this?
Aasync def protected_route(token: str = Depends(oauth2_scheme)): if token == None: return {"message": "Access granted"} raise HTTPException(status_code=401, detail="Unauthorized")
Basync def protected_route(token: str = Depends(oauth2_scheme)): if token != "secret123": raise HTTPException(status_code=401, detail="Unauthorized") return {"message": "Access granted"}
Casync def protected_route(token: str): if token == "secret123": return {"message": "Access granted"} raise HTTPException(status_code=403, detail="Forbidden")
Dasync def protected_route(token: str = Depends(oauth2_scheme)): if token == "Bearer secret123": return {"message": "Access granted"} raise HTTPException(status_code=401, detail="Unauthorized")
Step-by-Step Solution
Solution:
  1. Step 1: Use OAuth2PasswordBearer dependency

    We must use Depends(oauth2_scheme) to extract the token from the Authorization header.
  2. Step 2: Check token value correctly

    The token string is just the token without 'Bearer ' prefix, so compare directly to "secret123" and raise 401 if not matching.
  3. Final Answer:

    async def protected_route(token: str = Depends(oauth2_scheme)): if token != "secret123": raise HTTPException(status_code=401, detail="Unauthorized") return {"message": "Access granted"} -> Option B
  4. Quick Check:

    Compare token string directly to "secret123" [OK]
Quick Trick: Compare token string directly, no 'Bearer ' prefix included [OK]
Common Mistakes:
MISTAKES
  • Comparing token to 'Bearer secret123' including prefix
  • Not using Depends(oauth2_scheme) to get token
  • Returning access granted when token is None

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes