🗿

Firebase Authenticationの承認済みドメインの追加を自動化する

2022/11/10に公開

Identity Toolkit APIを使用してFirebase Authenticationの承認済みドメインをプログラマブルに追加する方法です。
該当のAPIドキュメントはこちらです。

準備

GCPコンソールのこちらからIdentity Platformを有効化します。
※Identity Platformの有効化は不要でした。(2022/11/10 加筆)

※有効化すると既存のFirebaseプロジェクトがGCIPと統合(アップグレード)されるようです。

続いてこちらからサービスアカウントを作成します。ロールは Firebase Authentication 管理者 にします。

サービスアカウントを作成したらサービスアカウントキーJSONを作成してローカルに保存しておきます。

コード

identitytoolkit/v3 ではサーバーから404が返ってきて動かなかったのでv2を使用しています。
Goで書くとこんな感じになります。

main.go
package main

import (
	"context"
	"log"

	"github.com/joho/godotenv"
	// v3ではなくv2を使う
	"google.golang.org/api/identitytoolkit/v2"
)

const (
	ProjectName = "firebase-project-name"
)

func main() {
	// .envにGOOGLE_APPLICATION_CREDENTIALSをセットしておく
	err := godotenv.Load(".env")
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	identitytoolkitService, err := identitytoolkit.NewService(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// projects/{project}/configの形
	name := "projects/" + ProjectName + "/config"

	var domains []string
	// 現在のリストを読み込む
	resp, err := identitytoolkitService.Projects.GetConfig(name).Do()
	if err != nil {
		log.Fatal(err)
	}
	domains = append(domains, resp.AuthorizedDomains...)

	// 追加したいドメイン
	domains = append(domains, "test.com")

	_, err = identitytoolkitService.Projects.UpdateConfig(name, &identitytoolkit.GoogleCloudIdentitytoolkitAdminV2Config{
		AuthorizedDomains: domains,
	}).Do()

	if err != nil {
		log.Fatal(err)
	}

	log.Print("DONE")
}

TypeScript(Node.js)で書くとこんな感じです。

index.ts
import * as dotenv from 'dotenv'
import {google} from 'googleapis'

dotenv.config()

const projectName = 'firebase-project-name'
const name = `projects/${projectName}/config`

async function main() {
  const identitytoolkit = google.identitytoolkit('v2')
  const auth = new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  })
  const authClient = await auth.getClient()
  google.options({auth: authClient})

  const getConfigRes = await identitytoolkit.projects.getConfig({name})

  if (getConfigRes.status !== 200) {
    throw new Error(getConfigRes.statusText)
  }

  const updateConfigRes = await identitytoolkit.projects.updateConfig({
    name,
    updateMask: 'authorizedDomains',
    requestBody: {
      // 追加したいドメイン
      authorizedDomains: [...getConfigRes.data.authorizedDomains ?? [], 'test.com']
    }
  })

  if (updateConfigRes.status !== 200) {
    throw new Error(updateConfigRes.statusText)
  }
}

main().catch(console.error)

Discussion