ユーザーが Google アカウントを使用して Firebase で認証できるようにすることができます。 Firebase SDK を使用して Google サインイン フローを実行するか、Sign In With Google ライブラリを使用して手動でサインイン フローを実行し、結果の ID トークンを Firebase に渡すことができます。
あなたが始める前に
- Firebase を JavaScript プロジェクトに追加します。
- Firebase コンソールでサインイン方法として Google を有効にします。
- Firebase コンソールで、 Authセクションを開きます。
- [サインイン方法] タブで、 Googleサインイン方法を有効にし、[保存] をクリックします。
Firebase SDK でログイン フローを処理する
ウェブアプリを構築している場合、Google アカウントを使用して Firebase でユーザーを認証する最も簡単な方法は、Firebase JavaScript SDK でログイン フローを処理することです。 (Node.js またはその他の非ブラウザー環境でユーザーを認証する場合は、サインイン フローを手動で処理する必要があります。)
Firebase JavaScript SDK でサインイン フローを処理するには、次の手順に従います。
- Google プロバイダー オブジェクトのインスタンスを作成します。
Web version 9
import { GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider();
Web version 8
var provider = new firebase.auth.GoogleAuthProvider();
- オプション: 認証プロバイダーから要求する追加の OAuth 2.0 スコープを指定します。スコープを追加するには、
addScope
を呼び出します。例えば:認証プロバイダーのドキュメントを参照してください。Web version 9
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
Web version 8
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
- オプション: 関連するカスタム OAuth パラメーターを明示的に渡さずにプロバイダーの OAuth フローをユーザーの優先言語にローカライズするには、OAuth フローを開始する前に Auth インスタンスの言語コードを更新します。例えば:
Web version 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
Web version 8
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
- オプション: OAuth 要求で送信する追加のカスタム OAuth プロバイダー パラメーターを指定します。カスタム パラメータを追加するには、OAuth プロバイダのドキュメントで指定されているキーと対応する値を含むオブジェクトを使用して、初期化されたプロバイダで
setCustomParameters
を呼び出します。例えば:予約済みの必須 OAuth パラメータは許可されておらず、無視されます。詳細については、認証プロバイダーのリファレンスを参照してください。Web version 9
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
Web version 8
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
- Google プロバイダー オブジェクトを使用して Firebase で認証します。ポップアップ ウィンドウを開くか、ログイン ページにリダイレクトすることで、ユーザーに Google アカウントでのログインを促すことができます。モバイル デバイスではリダイレクト方式が推奨されます。
- ポップアップ ウィンドウでサインインするには、
signInWithPopup
を呼び出します。また、Google API を使用して追加データを取得するために使用できる Google プロバイダーの OAuth トークンを取得できることにも注意してください。Web version 9
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); // ... });
Web version 8
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 Reference Docsを参照してください。
- サインイン ページにリダイレクトしてサインインするには、
signInWithRedirect
を呼び出します。次に、ページの読み込み時にWeb version 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
Web version 8
firebase.auth().signInWithRedirect(provider);
getRedirectResult
を呼び出して、Google プロバイダーの OAuth トークンを取得することもできます。これは、エラーをキャッチして処理できる場所でもあります。エラー コードのリストについては、 Auth Reference Docsを参照してください。Web version 9
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); // ... });
Web version 8
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; // ... });
- ポップアップ ウィンドウでサインインするには、
Chrome 拡張機能で Firebase を使用して認証する
Chrome 拡張アプリを作成している場合は、Chrome 拡張 ID を追加する必要があります。
- Firebase コンソールでプロジェクトを開きます。
- [認証]セクションで、[サインイン方法] ページを開きます。
- 次のような URI を承認済みドメインのリストに追加します:
chrome-extension://CHROME_EXTENSION_ID
Chrome 拡張機能は HTTP リダイレクトを使用できないため、ポップアップ操作 ( signInWithPopup
、 linkWithPopup
、およびreauthenticateWithPopup
) のみが Chrome 拡張機能で使用できます。認証ポップアップはブラウザ アクション ポップアップをキャンセルするため、ブラウザ アクション ポップアップではなく、バックグラウンド ページ スクリプトからこれらのメソッドを呼び出す必要があります。 popup メソッドは、 Manifest V2を使用する拡張機能でのみ使用できます。新しいマニフェスト V3では、ポップアップ操作をまったく実行できない Service Worker の形式のバックグラウンド スクリプトのみが許可されます。
Chrome 拡張機能のマニフェスト ファイルで、必ずhttps://apis.google.com
URL をcontent_security_policy
許可リストに追加してください。
次のステップ
ユーザーが初めてサインインすると、新しいユーザー アカウントが作成され、サインインに使用したユーザーの資格情報 (ユーザー名とパスワード、電話番号、または認証プロバイダー情報) にリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのサインイン方法に関係なく、プロジェクト内のすべてのアプリでユーザーを識別するために使用できます。
アプリでユーザーの認証ステータスを知るための推奨される方法は、
Auth
オブジェクトにオブザーバーを設定することです。その後、User
オブジェクトからユーザーの基本的なプロファイル情報を取得できます。ユーザーの管理を参照してください。Firebase Realtime Database と Cloud Storageセキュリティ ルールでは、サインインしているユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用してユーザーがアクセスできるデータを制御できます。
認証プロバイダーの資格情報を既存のユーザー アカウントにリンクすることで、ユーザーが複数の認証プロバイダーを使用してアプリにサインインできるようにすることができます。
ユーザーをサインアウトするには、 signOut
を呼び出します。
Web version 9
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
Web version 8
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });