Google I/O 2023 での Firebase の最新情報をご覧ください。詳細

ウェブサイトで Firebase Authentication を使ってみる

Firebase Authentication を使用すると、ユーザーがアプリにログインする際に、メールアドレスとパスワードによるログイン、フェデレーション ID プロバイダ(Google ログインや Facebook ログインなど)などの複数のログイン方法を使用できるようになります。このチュートリアルでは、Firebase Authentication を使って、メールアドレスとパスワードによるログインをアプリに追加する方法から始めます。

Authentication SDK を追加して初期化する

  1. まだ行っていない場合は、Firebase JS SDK をインストールして Firebase を初期化します

  2. Firebase Authentication JS SDK を追加して Firebase Authentication を初期化します。

Web version 9

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Firebase Authentication and get a reference to the service
const auth = getAuth(app);

Web version 8

import firebase from "firebase/app";
import "firebase/auth";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Firebase Authentication and get a reference to the service
const auth = firebase.auth();

(省略可)Firebase Local Emulator Suite でプロトタイピングおよびテストを行う

アプリによるユーザーの認証方法について見ていく前に、Authentication 機能のプロトタイピングとテストに使用できるツール、Firebase Local Emulator Suite をご紹介します。認証手法やプロバイダを検討している場合や、Authentication と Firebase セキュリティ ルールを使用して公開および非公開のデータで各種データモデルを試している場合、さらにログイン時の UI デザインのプロトタイプを作成している場合などは、ライブサービスをデプロイせずにローカルで作業できると便利です。

Local Emulator Suite の一部である Authentication エミュレータを使用すると、アプリはエミュレートされたデータベースのコンテンツと構成のほか、プロジェクト リソース(関数、他のデータベース、セキュリティ ルール)ともやり取りできます。

いくつかの手順を実施するだけで、Authentication エミュレータを使用できます。

  1. アプリのテスト構成にコード行を追加して、エミュレータに接続します。
  2. ローカル プロジェクトのディレクトリのルートから、firebase emulators:start を実行します。
  3. 対話型のプロトタイピングには Local Emulator Suite UI を使用し、非対話型のテストには Authentication エミュレータ REST API を使用します。

詳細な手順については、アプリを Authentication エミュレータに接続するをご覧ください。また、Local Emulator Suite の概要もご覧ください。

次に、ユーザーの認証方法を見てみましょう。

新しいユーザーを登録する

新規ユーザーがメールアドレスとパスワードを使用してアプリに登録できるフォームを作成します。ユーザーがフォームに入力したら、ユーザーから提供されたメールアドレスとパスワードを検証し、それらを createUserWithEmailAndPassword メソッドに渡します。

Web version 9

import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

Web version 8

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in
    var user = userCredential.user;
    // ...
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

既存のユーザーをログインさせる

既存のユーザーがメールアドレスとパスワードを使用してログインできるフォームを作成します。ユーザーがフォームに入力したら、signInWithEmailAndPassword メソッドを呼び出します。

Web version 9

import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });

Web version 8

firebase.auth().signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in
    var user = userCredential.user;
    // ...
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
  });

認証状態オブザーバーを設定してユーザーデータを取得する

ログインしているユーザーに関する情報が必要なアプリのページごとに、グローバル認証オブジェクトにオブザーバーをアタッチします。このオブザーバーは、ユーザーのログイン状態が変わるたびに呼び出されます。

onAuthStateChanged メソッドを使用してオブザーバーをアタッチします。ユーザーが正常にログインしたら、オブザーバーでユーザーに関する情報を取得できます。

Web version 9

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Web version 8

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

次のステップ

他の ID プロバイダと匿名ゲスト アカウントのサポートを追加する方法を学びます。