Closed8

firebase auth emulator で作成したユーザーの IdToken を取得したい

nbstshnbstsh

見たところ firebase admin sdk には、ログインユーザーの IdToken を取得するための api が生えていない。

firebase js client sdk を用いれば、ログインユーザーの IdToken を取得することができるが、server-side の project の devDependencies にわざわざ firebase js client sdk を含ませたくない...

調査の過程をメモしていく

nbstshnbstsh

firebase auth emulator の IdToken 生成

Sign in with email / password

You can sign in a user with an email and password by issuing an HTTP POST request to the Auth verifyPassword endpoint.

identitytoolkit.googleapis.com の email, password signIn の endpoint を local emulator で利用する。

https://firebase.google.com/docs/reference/rest/auth#section-sign-in-email-password

http://127.0.0.1:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${API_KEY} に email, password を POST request で送れば IdToken が取れる。

  const res = await fetch(
    `http://127.0.0.1:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${API_KEY}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: 'test@example.com',
        password: '12345678'
        returnSecureToken: true,
      }),
    },
  );
  const json = await res.json();
  console.log(json);

response の json の中身はこんな感じ↓

{
  kind: 'identitytoolkit#VerifyPasswordResponse',
  registered: true,
  localId: 'dummy',
  email: 'test@example.com',
  idToken: 'dummy',
  expiresIn: '3600'
}
nbstshnbstsh

Auth Emulator での custom token について

For security reasons, the Authentication emulator issues unsigned ID tokens, which are only accepted by other Firebase emulators, or the Firebase Admin SDK when configured. These tokens will be rejected by production Firebase services or Firebase Admin SDK running in production mode (e.g. the default behavior without the setup steps described above).

emulator が発行する ID は "署名なしの ID トークン" になるので、remote の Firebase Auth では弾かれるので注意。

https://firebase.google.com/docs/emulator-suite/connect_auth#id_tokens

The Authentication emulator does not validate the signature or expiry of custom tokens. This allows you to use hand-crafted tokens and re-use tokens indefinitely in prototyping and testing scenarios.

emulator での customToken による認証時に、署名と有効期限の検証はスキップされる。テスト時にこの辺を気にする必要はない。

https://firebase.google.com/docs/emulator-suite/connect_auth#custom_token_authentication

nbstshnbstsh

emulator が発行する ID は "署名なしの ID トークン" になるので、remote の Firebase Auth では弾かれるので注意。

=> auth emulator に接続した状態の firebase admin sdk で customToken を生成した場合、https://identitytoolkit.googleapis.com の Firebase Auth REST API を利用した idToken の生成は失敗するので注意。

emulator に接続している場合は、常に http://127.0.0.1:9099/identitytoolkit.googleapis.com の方を利用する。

このスクラップは2023/07/14にクローズされました