Skip to content

Instantly share code, notes, and snippets.

@alexpearce
Created June 17, 2022 03:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexpearce/73700474d8be770c0e5448cb09d885cb to your computer and use it in GitHub Desktop.
Save alexpearce/73700474d8be770c0e5448cb09d885cb to your computer and use it in GitHub Desktop.
FastAPI application demonstrating proper Bearer token usage.
import typing as t
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from starlette import status
app = FastAPI()
# Placeholder for a database containing valid token values
known_tokens = set(["api_token_abc123"])
# We will handle a missing token ourselves
get_bearer_token = HTTPBearer(auto_error=False)
class UnauthorizedMessage(BaseModel):
detail: str = "Bearer token missing or unknown"
async def get_token(
auth: t.Optional[HTTPAuthorizationCredentials] = Depends(get_bearer_token),
) -> str:
# Simulate a database query to find a known token
if auth is None or (token := auth.credentials) not in known_tokens:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=UnauthorizedMessage().detail,
)
return token
@app.get(
"/protected",
response_model=str,
responses={status.HTTP_401_UNAUTHORIZED: dict(model=UnauthorizedMessage)},
)
async def protected(token: str = Depends(get_token)):
return f"Hello, user! Your token is {token}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment