ユーザーは Firebase での認証に Google アカウントを使用できます。これには、Firebase SDK を使用して Google ログインフローを実行する方法と、「Google でログイン」ライブラリを使用し、生成された ID トークンを Firebase に渡すことでログインフローを手動で実行する方法があります。
始める前に
- Firebase を JavaScript プロジェクトに追加します。
- Firebase コンソールで、ログイン方法として Google を有効にします。
- Firebase コンソールで [Auth] セクションを開きます。
- [Sign-in method] タブで [Google] を有効にし、[保存] をクリックします。
Firebase SDK を使用したログインフローの処理
ウェブアプリをビルドする場合に、Google アカウントを使用して Firebase でユーザーを認証する最も簡単な方法は、Firebase JavaScript SDK でログインフローを処理することです(Node.js または他の非ブラウザ環境でユーザーを認証する場合、ログインフローを手動で処理する必要があります)。
Firebase JavaScript SDK でログインフローを処理する手順は次のとおりです。
- Google プロバイダ オブジェクトのインスタンスを作成します。
import { GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider();
var provider = new firebase.auth.GoogleAuthProvider();
- 省略可: 認証プロバイダにリクエストする追加の OAuth 2.0 スコープを指定します。スコープを追加するには、
addScope
を呼び出します。次に例を示します。provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
- 省略可: 関連するカスタム OAuth パラメータを明示的に渡すことなく、プロバイダの OAuth フローをローカライズしてユーザーの使用言語にするには、OAuth フローを開始する前に Auth インスタンスの言語コードを更新します。次に例を示します。
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
- 省略可: OAuth リクエストと一緒に送信する追加のカスタム OAuth プロバイダ パラメータを指定します。カスタム パラメータを追加するには、OAuth プロバイダのドキュメントで指定されたキーと、対応する値を含むオブジェクトで初期化されたプロバイダで
setCustomParameters
を呼び出します。provider.setCustomParameters({ 'login_hint': 'user@example.com' });
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
- Google プロバイダ オブジェクトを使用して Firebase での認証を行います。ユーザーに Google アカウントでログインするよう促すために、ポップアップ ウィンドウを表示するか、ログインページにリダイレクトします。モバイル デバイスではリダイレクトすることをおすすめします。
- ポップアップ ウィンドウでログインを行う場合は、
signInWithPopup
を呼び出します。import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; const auth = getAuth(); signInWithPopup(auth, provider) .then((result) => { // This gives you a Google Access Token. You can use it to access the Google API. const credential = GoogleAuthProvider.credentialFromResult(result); const token = credential.accessToken; // The signed-in user info. const user = result.user; // IdP data available using getAdditionalUserInfo(result) // ... }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... });
firebase.auth() .signInWithPopup(provider) .then((result) => { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a Google Access Token. You can use it to access the Google API. var token = credential.accessToken; // The signed-in user info. var user = result.user; // IdP data available in result.additionalUserInfo.profile. // ... }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
ここではエラーの検出と対応もできます。エラーコードのリストについては、Auth のリファレンス ドキュメントをご覧ください。
- ログインページにリダイレクトしてログインする場合は、
signInWithRedirect
を呼び出します。「signInWithRedirect」を使用する場合は、ベスト プラクティスに従ってください。import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
firebase.auth().signInWithRedirect(provider);
getRedirectResult
を呼び出すことによって、Google プロバイダの OAuth トークンを取得することもできます。import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth"; const auth = getAuth(); getRedirectResult(auth) .then((result) => { // This gives you a Google Access Token. You can use it to access Google APIs. const credential = GoogleAuthProvider.credentialFromResult(result); const token = credential.accessToken; // The signed-in user info. const user = result.user; // IdP data available using getAdditionalUserInfo(result) // ... }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... });
firebase.auth() .getRedirectResult() .then((result) => { if (result.credential) { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a Google Access Token. You can use it to access the Google API. var token = credential.accessToken; // ... } // The signed-in user info. var user = result.user; // IdP data available in result.additionalUserInfo.profile. // ... }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
- ポップアップ ウィンドウでログインを行う場合は、
account-exists-with-different-credential エラーの処理
Firebase コンソールで [1 つのメールアドレスにつき 1 つのアカウント] 設定を有効にしている場合、Firebase ユーザーが、あるプロバイダ(Facebook など)用にすでに存在しているメールアドレスを使って別のプロバイダ(Google など)にログインしようとすると、AuthCredential
オブジェクト(Google ID トークン)とともにエラー auth/account-exists-with-different-credential
がスローされます。目的のプロバイダにログインするには、まず既存のプロバイダ(Facebook)にログインしてから、目的のプロバイダの AuthCredential
(Google ID トークン)にリンクする必要があります。
ポップアップ モード
signInWithPopup
を使用する場合、次のようなコードによって auth/account-exists-with-different-credential
エラーを処理できます。
import { getAuth, linkWithCredential, signInWithPopup, GoogleAuthProvider, } from "firebase/auth"; try { // Step 1: User tries to sign in using Google. let result = await signInWithPopup(getAuth(), new GoogleAuthProvider()); } catch (error) { // Step 2: User's email already exists. if (error.code === "auth/account-exists-with-different-credential") { // The pending Google credential. let pendingCred = error.credential; // Step 3: Save the pending credential in temporary storage, // Step 4: Let the user know that they already have an account // but with a different provider, and let them choose another // sign-in method. } } // ... try { // Step 5: Sign the user in using their chosen method. let result = await signInWithPopup(getAuth(), userSelectedProvider); // Step 6: Link to the Google credential. // TODO: implement `retrievePendingCred` for your app. let pendingCred = retrievePendingCred(); if (pendingCred !== null) { // As you have access to the pending credential, you can directly call the // link method. let user = await linkWithCredential(result.user, pendingCred); } // Step 7: Continue to app. } catch (error) { // ... }
リダイレクト モード
このエラーはリダイレクト モードでも同様の方法で処理されますが、ページをリダイレクトする間、保留された認証情報をキャッシュに保存する必要がある点が異なります(セッション ストレージなどを使用します)。
高度: 手動によるログインフローの処理
Google アカウントを使用して Firebase で認証を行えるようにするために、「Google でログイン」ライブラリを使用してログインフローを処理することもできます。
- 統合ガイドに沿って、「Google でログイン」をアプリに統合します。必ず Firebase プロジェクト用の生成された Google クライアント ID を使用して Google ログインを構成します。プロジェクトの Google クライアント ID は、プロジェクトの Developers Console の認証情報ページにあります。
- ログインによって発生するコールバックで、Google の認証応答からの ID トークンを Firebase 認証情報と交換し、それを使用して Firebase での認証を行います。
function handleCredentialResponse(response) { // Build Firebase credential with the Google ID token. const idToken = response.credential; const credential = GoogleAuthProvider.credential(idToken); // Sign in with credential from the Google user. signInWithCredential(auth, credential).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.email; // The credential that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... }); }
高度: Node.js 内で Firebase で認証する
Node.js アプリケーションで Firebase により認証する手順は、次のとおりです。
- Google アカウントにログインし、Google ID トークンを取得します。これには複数の方法があります。例:
- アプリにブラウザのフロントエンドがある場合、手動でログインフローを処理するセクションに記載されている Google ログインを使用します。auth レスポンスから Google ID トークンを取得します。
次に、このトークンを Node.js アプリに送信します。var id_token = googleUser.getAuthResponse().id_token
- アプリがテレビなどの入力機能が制限されたデバイス上で実行される場合、テレビおよびデバイスでの Google ログインの手順を行います。
- アプリにブラウザのフロントエンドがある場合、手動でログインフローを処理するセクションに記載されている Google ログインを使用します。auth レスポンスから Google ID トークンを取得します。
- ユーザーの Google ID トークンを取得した後、そのトークンを使用して認証情報オブジェクトをビルドしてから、認証情報でユーザーにログインします。
import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth"; // Build Firebase credential with the Google ID token. const credential = GoogleAuthProvider.credential(id_token); // Sign in with credential from the Google user. const auth = getAuth(); signInWithCredential(auth, credential).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... });
// Build Firebase credential with the Google ID token. var credential = firebase.auth.GoogleAuthProvider.credential(id_token); // Sign in with credential from the Google user. firebase.auth().signInWithCredential(credential).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
Chrome 拡張機能で Firebase による認証を行う
Chrome 拡張機能アプリを作成する場合は、画面外ドキュメントのガイドをご覧ください。
Google ログインのリダイレクト ドメインのカスタマイズ
プロジェクトの作成時に、Firebase は次のようなプロジェクト固有のサブドメインをプロビジョニングします。https://my-app-12345.firebaseapp.com
これは、OAuth ログインのリダイレクト メカニズムとしても使用されます。このドメインは、サポートされているすべての OAuth プロバイダに許可される必要があります。この場合、ユーザーが Google にログインしている間、アプリケーションにリダイレクトする前に、Continue to: https://my-app-12345.firebaseapp.com のようにドメインを含むメッセージが表示される可能性があります。
サブドメインが表示されないようにするには、Firebase Hosting でカスタム ドメインを設定します。
- Hosting 用にドメインを設定するの手順 1~3 を行います。ドメインの所有権を確認すると、Hosting はカスタム ドメイン向けに SSL 証明書をプロビジョニングします。
- Firebase コンソールで、認可済みドメインのリストにカスタム ドメイン
auth.custom.domain.com
を追加します。 - Google のデベロッパー コンソールまたは OAuth 設定ページで、リダイレクト ページの URL(
https://auth.custom.domain.com/__/auth/handler
)を許可リストに登録します。これにより、カスタム ドメインでアクセス可能になります。 - JavaScript ライブラリを初期化するときに、
authDomain
フィールドにカスタム ドメインを指定します。var config = { apiKey: '...', // Changed from '
PROJECT_ID .firebaseapp.com'. authDomain: 'auth.custom.domain.com', databaseURL: 'https://PROJECT_ID .firebaseio.com', projectId: 'PROJECT_ID ', storageBucket: ' ', messagingSenderId: 'PROJECT_ID .firebasestorage.appSENDER_ID ' }; firebase.initializeApp(config);
次のステップ
ユーザーが初めてログインすると、新しいユーザー アカウントが作成され、ユーザーがログイン時に使用した認証情報(ユーザー名とパスワード、電話番号、または認証プロバイダ情報)にアカウントがリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのログイン方法にかかわらず、プロジェクトのすべてのアプリでユーザーを識別するために使用できます。
-
アプリでユーザーの認証ステータスを把握するには、
Auth
オブジェクトにオブザーバーを設定することをおすすめします。これによって、ユーザーの基本的なプロフィール情報をUser
オブジェクトから取得できます。ユーザーを管理するをご覧ください。 Firebase Realtime Database と Cloud Storage のセキュリティ ルールでは、ログイン済みユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用して、ユーザーがアクセスできるデータを制御できます。
既存のユーザー アカウントに認証プロバイダの認証情報をリンクすることで、ユーザーは複数の認証プロバイダを使用してアプリにログインできるようになります。
ユーザーのログアウトを行うには、signOut
を呼び出します。
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });