1
1

More than 1 year has passed since last update.

fastapi-cloudauthをFirebase認証とともに使う際の備忘録

Last updated at Posted at 2021-10-30

※取り急ぎ書いている内容なので、書き方が雑なのはご了承ください。

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に載っているインストラクションに従う。

main.py
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キーを取ってきておく

Screenshot 2021-10-30 135158.png

今回の場合だと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_ADDRESSYOUR_PASSWORDはそれぞれFirebase Authで作成したユーザーの情報を入力し、curlを叩くとJSONが帰ってくるので、idTokenの値を取得、FastAPIで作成したAPIのBearerの部分に入れておく。

1
1
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
1
1