Google でのユーザーのログイン

このドキュメントでは、Identity Platform を使用して Google でユーザーのログインを行う方法について説明します。

始める前に

このチュートリアルは、すでに Identity Platform が有効であり、HTML と JavaScript を使用して作成された基本的なウェブアプリがあることを前提としています。その方法については、クイックスタートをご覧ください。

Google をプロバイダとして構成する

Google を ID プロバイダとして構成するには:

  1. Google Cloud コンソールで [ID プロバイダ] ページに移動します。

    [ID プロバイダ] ページに移動

  2. [プロバイダを追加] をクリックします。

  3. リストから [Google] を選択します。

  4. Google ウェブ クライアント IDウェブ シークレットを入力します。ID とシークレットをまだ持っていない場合は、API とサービス ページから取得できます。

  5. [Google の構成] に表示されている URI を、Google アプリケーションの有効な OAuth リダイレクト URI として構成します。

  6. [承認済みドメイン] で [ドメインを追加] をクリックして、アプリのドメインを登録します。開発目的の場合は、localhost はデフォルトですでに有効になっています。

  7. [アプリケーションの構成] で [設定の詳細] をクリックします。このスニペットをアプリのコードにコピーして、Identity Platform Client SDK を初期化します。

  8. [保存] をクリックします。

Client SDK を使用したユーザーのログイン

  1. Google プロバイダ オブジェクトのインスタンスを作成します。

    Web バージョン 9

    import { GoogleAuthProvider } from "firebase/auth";
    
    const provider = new GoogleAuthProvider();

    Web バージョン 8

    var provider = new firebase.auth.GoogleAuthProvider();
  1. 省略可: OAuth スコープを追加します。スコープとは、Google からどんなデータを要求するかを指定します。より機密性の高いデータには、特定のスコープが必要になる場合があります。アプリが必要とするスコープを判断するには、プロバイダのドキュメントをご覧ください。

    Web バージョン 9

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');

    Web バージョン 8

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  1. 省略可: 認証フローをローカライズします。言語を指定するか、デバイスのデフォルトの言語を使用できます。

    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();
  2. 省略可: その他のカスタム OAuth パラメータを指定します。これらは Google 特有であり、通常は認証エクスペリエンスのカスタマイズに使用されます。OAuth または Identity Platform で予約されているパラメータを渡すことはできません。

Web バージョン 9

provider.setCustomParameters({
  'login_hint': 'user@example.com'
});

Web バージョン 8

provider.setCustomParameters({
  'login_hint': 'user@example.com'
});
  1. 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() を呼び出します。

    signInWithRedirectlinkWithRedirectreauthenticateWithRedirect を使用する場合は、ベスト プラクティスに従ってください。

    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

手動でのユーザーのログイン

Client SDK を使用しない場合は、次の手順でログイン フローを手動で処理することもできます。

  1. デベロッパー向けドキュメントの手順に沿って、Google 認証をアプリに統合します。

  2. 前の手順で実装したフローを使用して、Google でユーザーのログインを行います。

  3. Google から受け取ったトークンを Identity Platform の認証情報と交換します。

    Web バージョン 9

    import { GoogleAuthProvider } from "firebase/auth";
    
    const credential = GoogleAuthProvider.credential(idToken);

    Web バージョン 8

    var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
  4. 認証情報を使用して、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;
        // ...
      });

次のステップ