0
0
FastAPIframework~10 mins

OAuth2 password flow 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 OAuth2PasswordBearer class from FastAPI.

FastAPI
from fastapi.security import [1]
Drag options to blanks, or click blank then click option'
AAPIKeyHeader
BOAuth2PasswordRequestForm
COAuth2PasswordBearer
DHTTPBasic
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing OAuth2PasswordBearer with OAuth2PasswordRequestForm.
Importing HTTPBasic instead of OAuth2PasswordBearer.
2fill in blank
medium

Complete the code to create an OAuth2PasswordBearer instance with the token URL '/token'.

FastAPI
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=[1])
Drag options to blanks, or click blank then click option'
A"/login"
B"/access"
C"/auth"
D"/token"
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/login' or other URLs that do not match the token endpoint.
Forgetting to put quotes around the URL string.
3fill in blank
hard

Fix the error in the dependency injection to get the token from the OAuth2 scheme.

FastAPI
async def read_items(token: str = [1]):
Drag options to blanks, or click blank then click option'
Aoauth2_scheme()
BDepends(oauth2_scheme)
CDepends(oauth2_scheme())
Doauth2_scheme
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the oauth2_scheme inside Depends, which causes an error.
Not using Depends at all.
4fill in blank
hard

Fill both blanks to define a token endpoint that uses OAuth2PasswordRequestForm and returns a token.

FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post("/token")
async def login(form_data: [1] = Depends()):
    return {"access_token": form_data.[2], "token_type": "bearer"}
Drag options to blanks, or click blank then click option'
AOAuth2PasswordRequestForm
Busername
Cpassword
DOAuth2PasswordBearer
Attempts:
3 left
💡 Hint
Common Mistakes
Using OAuth2PasswordBearer instead of OAuth2PasswordRequestForm.
Accessing form_data.password instead of username for the token.
5fill in blank
hard

Fill all three blanks to create a protected route that extracts the token and returns a welcome message.

FastAPI
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")

@app.get("/users/me")
async def read_users_me(token: str = Depends([1])):
    if not token:
        raise HTTPException(status_code=401, detail="Invalid authentication")
    return {"message": f"Welcome, [2]! Your token is [3]."}
Drag options to blanks, or click blank then click option'
Aoauth2_scheme
Buser
Ctoken
DtokenUrl
Attempts:
3 left
💡 Hint
Common Mistakes
Using Depends(oauth2_scheme()) instead of Depends(oauth2_scheme).
Using tokenUrl instead of oauth2_scheme.
Using undefined variables in the message.