OAuth2PasswordBearer is FastAPI’s Bearer token authentication scheme.
OAuth2 scheme
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException
# tokenUrl — the URL used to obtain a token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")
Login form (OAuth2PasswordRequestForm)
from fastapi import APIRouter
from fastapi.security import OAuth2PasswordRequestForm
router = APIRouter(prefix="/auth")
@router.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends()):
# form_data.username
# form_data.password
user = authenticate(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=401, detail="Invalid credentials")
token = create_token(user.id)
return {
"access_token": token,
"token_type": "bearer", # required!
}
Using the token in a request
# Obtain a token
curl -X POST /auth/token \
-F "username=user" \
-F "password=pass"
# Use the token
curl /api/tasks/ \
-H "Authorization: Bearer eyJhbGci..."
Extracting the token in an endpoint
@app.get("/tasks/")
async def list_tasks(token: str = Depends(oauth2_scheme)):
# token — raw token string
user = decode_token(token)
return get_tasks(user)
Optional authentication
from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
@app.get("/tasks/")
def list_tasks(token: str | None = Depends(oauth2_scheme)):
if token:
user = decode_token(token)
return get_user_tasks(user)
return get_public_tasks()
Refresh tokens
class TokenResponse(BaseModel):
access_token: str
refresh_token: str
token_type: str = "bearer"
expires_in: int
@router.post("/token", response_model=TokenResponse)
def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate(form_data.username, form_data.password)
return {
"access_token": create_access_token(user.id),
"refresh_token": create_refresh_token(user.id),
"expires_in": 1800,
}
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!