1
0

More than 3 years have passed since last update.

Firebase AuthenticationのIDトークンをHTTPクライアントのリクエストヘッダーに渡す

Last updated at Posted at 2020-12-11

レッドインパルスのたかけんです。
REDIMPULZ Advent Calendar 2020 の11日目のエントリーです。

自前のバックエンドの認証にFirebase Authenticationを使う

バックエンドの開発で、認証にFirebase Authenticationを使用して、認証をする場合があります。
その際にFirebase Authenticationで取得したIDトークンをAPIリクエスト毎にリクエストヘッダーに含める方法です。

HTTPクライアントには、ky を使用しています。

lib/firebase
import firebase from 'firebase/app';
import 'firebase/auth';

firebase.apps.length
  ? firebase.app()
  : firebase.initializeApp({
      // 認証情報
    });

export const auth = firebase.auth();
http
import ky from 'ky';
import firebase from 'firebase';

import { auth } from '@/lib/firebase';

const getUser = () =>
  new Promise<firebase.User>((resolve, reject) =>
    auth.onAuthStateChanged((user) => (user ? resolve(user) : reject()))
  );

const http = ky.create({
  prefixUrl: // APIのエンドポイントのプレフィックス,
  hooks: {
    beforeRequest: [
      async (request) => {
        try {
          const user = await getUser();
          const token = await user.getIdToken();
          request.headers.set('Authorization', `Bearer ${token}`);
        } catch (error) {
          console.log(error);
        }
      },
    ],
  },
});

export default http;

要点

  • onAuthStateChangedのコールバックでuserが取得できるので、Promiseでラップして同期的にuserを取得できるようにする
  • beforeRequestはAPIリクエスト毎に呼ばれるのasync/awaitでgetUserを実行し、userを取得
  • userのgetIdTokenでIDトークンを取得
  • リクエストヘッダーのAuthorizationにIDトークンをセットする

まとめ

Firebase AuthenticationのIDトークンをAPIクライアントのリクエストヘッダーに渡す方法でした。
ky では無く axios を使っている人も多いと思いますが、その場合は、interceptorsを使って同様のことができるかと思います。

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