3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

fastapi-jwt-authを使用して Swagger UI に Authorize オプションを表示する方法

Posted at

FastAPIでJWTトークンによるBearer認証を、fastapi-jwt-authライブラリを使用して実装する際、Swagger UI に Authorize オプションを表示する方法についての議事録です。

手順は、HTTPBearerスキームをDependsを使って依存関係として注入します。
これにより、Swagger UIに認証ヘッダーを入力するフィールドが表示されます。

公式ドキュメントのコードをベースに、追加変更した部分にDiffを表現しています。
公式ドキュメント:https://indominusbyte.github.io/fastapi-jwt-auth/usage/basic/

main.py
from fastapi import Depends, HTTPException, status
+ from fastapi.security import HTTPBearer
from fastapi_jwt_auth import AuthJWT
from fastapi import FastAPI

app = FastAPI()

+ bearer_scheme = HTTPBearer()

class User(BaseModel):
    username: str
    password: str

class Settings(BaseModel):
    authjwt_secret_key: str = "secret"

@AuthJWT.load_config
def get_config():
    return Settings()

@app.post("/login")
def login(user: User, Authorize: AuthJWT = Depends()):
    if user.username =='test' and user.password =='test':
        access_token = Authorize.create_access_token(subject=user.username)
        return {"access_token": access_token}
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid username or password"
        )

+ @app.get("/protected", dependencies=[Depends(bearer_scheme)])
def protected(Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    current_user = Authorize.get_jwt_subject()
    return {"user": current_user}

Swagger UIを開くとAuthorizeボタンが表示されます。
image.png

エンドポイント('/login')を使ってアクセストークンを取得します。
これはPOSTリクエストで、ユーザ名とパスワードをリクエストボディに含めます。
入力したらExecuteをクリック。
image.png

トークンがレスポンスされたのが確認できます。
取得したアクセストークンをコピーします。
image.png

Authorizeボタンをクリックし、コピーしたアクセストークンを入力し、AuthorizeとCloseをクリックします。
image.png

これで保護されたエンドポイント(下記例では '/user')にリクエストを送信するときにアクセストークンが認証ヘッダーに含まれます。
リクエストを送信してレスポンスを確認します。
image.png

3
0
0

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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?