Bird
0
0

You want to secure a FastAPI endpoint so only users with a valid OAuth2 password flow token can access it. Which approach correctly uses OAuth2PasswordBearer and token verification?

hard🚀 Application Q15 of 15
FastAPI - Authentication and Security
You want to secure a FastAPI endpoint so only users with a valid OAuth2 password flow token can access it. Which approach correctly uses OAuth2PasswordBearer and token verification?
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')

def verify_token(token: str):
    if token != 'validtoken':
        raise HTTPException(status_code=401, detail='Invalid token')

@app.get('/secure-data')
async def secure_data(token: str = Depends(oauth2_scheme)):
    verify_token(token)
    return {'data': 'secret info'}
AIncorrect: verify_token should return True/False, not raise exceptions.
BIncorrect: tokenUrl should be '/secure-data' not 'token'.
CCorrect: uses OAuth2PasswordBearer and verifies token before returning data.
DIncorrect: OAuth2PasswordBearer cannot be used with GET endpoints.
Step-by-Step Solution
Solution:
  1. Step 1: Check OAuth2PasswordBearer usage

    oauth2_scheme is created with tokenUrl='token', which is correct for password flow token endpoint.
  2. Step 2: Verify token validation logic

    verify_token raises HTTPException on invalid token, which is proper for access control.
  3. Step 3: Confirm endpoint dependency and response

    secure_data depends on oauth2_scheme to get token, verifies it, then returns protected data.
  4. Final Answer:

    Correct: uses OAuth2PasswordBearer and verifies token before returning data. -> Option C
  5. Quick Check:

    Use OAuth2PasswordBearer + verify token = secure endpoint [OK]
Quick Trick: Use OAuth2PasswordBearer with tokenUrl and verify token [OK]
Common Mistakes:
MISTAKES
  • Setting wrong tokenUrl in OAuth2PasswordBearer
  • Not raising exceptions on invalid token
  • Thinking OAuth2PasswordBearer can't be used with GET

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes