※取り急ぎ書いている内容なので、書き方が雑なのはご了承ください。
FastAPIと認証基盤を連携させる際、様々な方法があるが、そのうちの1つにfastapi-cloudauthライブラリを使用する方法がある。
fastapi-cloudauthでは、Auth0やAWS Cognito、Firebase Authなど使うことができるが、そのうちのFirebase Authと連携させたときにつまずいた部分があったので、備忘録としてここに残しておく。
ライブラリのインストール
Firebase Authを使う場合、fastapi-cloudauth
以外にcryptography
というライブラリも同時に導入しなければいけないらしい。
pip install fastapi-cloudauth
pip install cryptography
※pipコマンドを使用しているので、pipenv, poetryなどでは適宜読み替えること
FastAPI上でのルーティング設定
ここは無難にreadmeに載っているインストラクションに従う。
import os
from fastapi import FastAPI, Depends
from fastapi_cloudauth.firebase import FirebaseCurrentUser, FirebaseClaims
app = FastAPI()
get_current_user = FirebaseCurrentUser(
project_id=os.environ["PROJECT_ID"]
)
@app.get("/user/")
def secure_user(current_user: FirebaseClaims = Depends(get_current_user)):
# ID token is valid and getting user info from ID token
return f"Hello, {current_user.user_id}"
PROJECT_ID
が環境変数として設定されているが、これはFirebaseのプロジェクトID (下の画像で言うmy-awesome-project
)を入れておく。
認証を試してみる
Firebaseのプロジェクト設定へ行き、ウェブAPIキーを取ってきておく
今回の場合だとYOUR_WEB_API_KEY
にしてある。
curl -XPOST -H "Content-type: application/json" -d '{
"email":"YOUR_EMAIL_ADDRESS",
"password":"YOUR_PASSWORD",
"returnSecureToken":true
}' 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=YOUR_WEB_API_KEY'
YOUR_WEB_API_KEY
は先程のウェブAPIキー、YOUR_EMAIL_ADDRESS
とYOUR_PASSWORD
はそれぞれFirebase Authで作成したユーザーの情報を入力し、curlを叩くとJSONが帰ってくるので、idToken
の値を取得、FastAPIで作成したAPIのBearerの部分に入れておく。