Complete the code to import the correct FastAPI security class for bearer token handling.
from fastapi.security import [1]
The HTTPBearer class is used in FastAPI to handle bearer token authentication.
Complete the code to create an instance of the HTTPBearer security scheme.
security = [1]()Creating an instance of HTTPBearer allows FastAPI to extract bearer tokens from requests.
Fix the error in the dependency function to correctly extract the bearer token string.
async def get_token(credentials: HTTPAuthorizationCredentials = Depends(security)): return credentials.[1]
The HTTPAuthorizationCredentials object has a token attribute that contains the bearer token string.
Fill both blanks to define a FastAPI route that requires a bearer token and returns it.
from fastapi import FastAPI, Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials app = FastAPI() security = HTTPBearer() @app.get("/token") async def read_token(credentials: [1] = Depends(security)): return {"token": credentials.[2]
The route depends on HTTPAuthorizationCredentials to get the credentials object, and returns the token attribute.
Fill all three blanks to create a dependency that validates the bearer token prefix and returns the token string.
from fastapi import HTTPException, status async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)): if credentials.scheme != [1]: raise HTTPException(status_code=[2], detail="Invalid authentication scheme") return credentials.[3]
The scheme must be "Bearer" to accept bearer tokens. If not, raise 401 Unauthorized. Return the token string.
