5
1

More than 1 year has passed since last update.

FastAPIでBearerトークンを抽出する

Last updated at Posted at 2021-12-30

小ネタ。

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

5
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1