小ネタ。
FastAPIでAuthorization: Bearer {token}のようにヘッダで送られてくるトークンを使って認証したい場合に、トークン取得処理の自前実装が不要になる。
コード
Dependsを使ってDIチックに処理できるので嬉しい
dependencies.py
from fastapi import Request, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
async def get_bearer_token(
request: Request,
authorization: HTTPAuthorizationCredentials = Depends(HTTPBearer())
) -> str:
token = authorization.credentials
return token
await bearer(request)としている部分は、HTTPBearerクラスの__call__が該当処理。
ソースコード: fastapi/http.py at master · tiangolo/fastapi