Google でユーザーのログインを行う
このドキュメントでは、Identity Platform を使用して Google でユーザーのログインを行う方法について説明します。
始める前に
このチュートリアルは、すでに Identity Platform が有効であり、HTML と JavaScript を使用して作成された基本的なウェブアプリがあることを前提としています。Identity Platform を有効にしてログインする方法については、クイックスタートをご覧ください。
Google をプロバイダとして構成する
Google を ID プロバイダとして構成するには:
- Google Cloud コンソールで [ID プロバイダ] ページに移動します。
- [プロバイダを追加] をクリックします。
- リストから [Google] を選択します。
- Google ウェブ クライアント ID とウェブ シークレットを入力します。ID とシークレットをまだ持っていない場合は、 API とサービス ページから取得できます。
- 外部クライアント ID からのアクセスを許可するには、[ 追加] をクリックして、クライアント ID を追加します。
- 同意画面を構成するには、[画面を構成] をクリックします。Google Auth Platform ページが別のタブで開きます。
- [Google Auth Platform] ページで、 OAuth 同意画面を構成します。
-
[ID プロバイダ] ページに戻り、[プロジェクト設定] サイドペインで [ドメインを追加] をクリックして、アプリのドメインを追加します。
本番環境プロジェクトに
localhost
を含めないことをおすすめします。 - [アプリケーションの構成] セクションで、[詳細を設定] をクリックします。このスニペットをアプリのコードにコピーして、Identity Platform Client SDK を初期化します。
- [保存] をクリックします。
クライアント SDK を使用してユーザーをログインさせる
-
Google プロバイダ オブジェクトのインスタンスを作成します。
Web バージョン 9
import { GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider();
Web バージョン 8
var provider = new firebase.auth.GoogleAuthProvider();
-
省略可: OAuth スコープを追加します。スコープとは、Google からどんなデータを要求するかを指定します。より機密性の高いデータには、特定のスコープが必要になる場合があります。アプリが必要とするスコープを判断するには、プロバイダのドキュメントをご覧ください。
Web バージョン 9
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
Web バージョン 8
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
-
省略可: 認証フローをローカライズします。言語を指定するか、デバイスのデフォルトの言語を使用できます。
Web バージョン 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
Web バージョン 8
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
-
省略可: その他のカスタム OAuth パラメータを指定します。これらは Google 特有であり、通常は認証エクスペリエンスのカスタマイズに使用されます。OAuth または Identity Platform で予約されているパラメータを渡すことはできません。
Web バージョン 9
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
Web バージョン 8
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
-
Google プロバイダ オブジェクトを使用して、ユーザーのログインを行います。ポップアップ ウィンドウを開く、または現在のページをリダイレクトできます。モバイル デバイスでは、リダイレクトの方がユーザーにとってより簡単な方法です。
ポップアップを表示するには、
signInWithPopup()
を呼び出します。Web バージョン 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 バージョン 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; // ... });
ページをリダイレクトするには、まず
signInWithRedirect()
を呼び出します。signInWithRedirect
、linkWithRedirect
、reauthenticateWithRedirect
を使用する場合は、ベスト プラクティスに従ってください。Web バージョン 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
Web バージョン 8
firebase.auth().signInWithRedirect(provider);
次に、ページが読み込まれるときに
getRedirectResult()
を呼び出すことによって、Google トークンを取得します。Web バージョン 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 バージョン 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; // ... });
アクセス トークンを取得したら、それを使用して Google API を呼び出すことができます。次に例を示します。
REST
curl -H "Authorization: Bearer [TOKEN]" https://www.googleapis.com/oauth2/v2/userinfo
ユーザーを手動でログインさせる
クライアント SDK を使用しない場合は、次の手順でログイン フローを手動で処理することもできます。
- デベロッパー向けドキュメントの手順に沿って、Google 認証をアプリに統合します。
- 前の手順で実装したフローを使用して、Google でユーザーのログインを行います。
-
Google から受け取ったトークンを Identity Platform の認証情報と交換します。
Web バージョン 9
import { GoogleAuthProvider } from "firebase/auth"; const credential = GoogleAuthProvider.credential(idToken);
Web バージョン 8
var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
-
認証情報を使用して、Identity Platform でユーザーのログインを行います。
Web バージョン 9
import { getAuth, signInWithCredential } from "firebase/auth"; // Sign in with the credential from the user. const auth = getAuth(); signInWithCredential(auth, credential) .then((result) => { // Signed in // ... }) .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; // ... });
Web バージョン 8
// Sign in with the credential from the user. firebase.auth() .signInWithCredential(credential) .then((result) => { // Signed in // ... }) .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; // ... });
次のステップ
- Identity Platform ユーザーの詳細を確認する。
- 他の ID プロバイダでユーザーのログインを行う。