0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

FastAPIは高性能で使いやすいPythonのWebフレームワークです。このフレームワークでBasic認証を実装する方法を紹介します。

1. 必要なライブラリのインストール

まず、必要なライブラリをインストールします。

pip install fastapi uvicorn python-multipart

2. Basic認証の実装

以下は、FastAPIでBasic認証を実装する基本的なコードです。

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets

app = FastAPI()
security = HTTPBasic()

def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    correct_username = secrets.compare_digest(credentials.username, "user")
    correct_password = secrets.compare_digest(credentials.password, "password")
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

@app.get("/")
def read_root(username: str = Depends(get_current_username)):
    return {"message": f"Hello, {username}!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

3. コードの説明

  1. HTTPBasicクラスを使用してBasic認証を設定します。
  2. get_current_username関数で認証ロジックを実装します。
    • secrets.compare_digestを使用して、タイミング攻撃を防ぎます。
    • 認証が失敗した場合、401エラーを返します。
  3. エンドポイントにDepends(get_current_username)を追加して、アクセス時に認証を要求します。

4. 動作確認

  1. 上記のコードをmain.pyとして保存します。

  2. ターミナルでuvicorn main:app --reloadを実行してサーバーを起動します。

  3. ブラウザでhttp://localhost:8000にアクセスすると、認証ダイアログが表示されます。
    image.png

  4. ユーザー名「user」、パスワード「password」で認証すると、メッセージが表示されます。
    image.png

まとめ

FastAPIでBasic認証を実装する方法を紹介しました。この方法は簡単に実装できますが、プロダクション環境では、よりセキュアな認証方法(例:OAuth2やJWT)の使用を検討することをお勧めします。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?