Bird
0
0
FastAPIframework~10 mins

Bearer token handling in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct FastAPI security class for bearer token handling.

FastAPI
from fastapi.security import [1]
Drag options to blanks, or click blank then click option'
AHTTPBasic
BAPIKeyHeader
COAuth2PasswordBearer
DHTTPBearer
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing OAuth2PasswordBearer which is for OAuth2 flows, not simple bearer tokens.
Choosing HTTPBasic which is for basic auth, not bearer tokens.
2fill in blank
medium

Complete the code to create an instance of the HTTPBearer security scheme.

FastAPI
security = [1]()
Drag options to blanks, or click blank then click option'
AOAuth2PasswordBearer
BHTTPBearer
CHTTPBasic
DAPIKeyHeader
Attempts:
3 left
💡 Hint
Common Mistakes
Instantiating OAuth2PasswordBearer which requires a token URL.
Using HTTPBasic which is unrelated to bearer tokens.
3fill in blank
hard

Fix the error in the dependency function to correctly extract the bearer token string.

FastAPI
async def get_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    return credentials.[1]
Drag options to blanks, or click blank then click option'
Atoken
Btoken_type
Ccredentials
Daccess_token
Attempts:
3 left
💡 Hint
Common Mistakes
Using token_type which is usually 'Bearer', not the token itself.
Using access_token which is not an attribute of HTTPAuthorizationCredentials.
4fill in blank
hard

Fill both blanks to define a FastAPI route that requires a bearer token and returns it.

FastAPI
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]
Drag options to blanks, or click blank then click option'
AHTTPAuthorizationCredentials
BHTTPBearer
Ctoken
Dtoken_type
Attempts:
3 left
💡 Hint
Common Mistakes
Using HTTPBearer as the parameter type instead of HTTPAuthorizationCredentials.
Returning token_type instead of token.
5fill in blank
hard

Fill all three blanks to create a dependency that validates the bearer token prefix and returns the token string.

FastAPI
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]
Drag options to blanks, or click blank then click option'
A"Bearer"
Bstatus.HTTP_401_UNAUTHORIZED
Ctoken
D"Basic"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for "Basic" scheme instead of "Bearer".
Using wrong status code like 403 instead of 401.
Returning scheme or token_type instead of token.