Memproses login pengguna dengan Google

Dokumen ini menunjukkan cara menggunakan Identity Platform untuk memproses login pengguna dengan Google.

Sebelum memulai

Tutorial ini mengasumsikan bahwa Anda telah mengaktifkan Identity Platform, dan memiliki aplikasi web dasar yang ditulis menggunakan HTML dan JavaScript. Lihat Panduan Memulai untuk mempelajari caranya.

Mengonfigurasi Google sebagai penyedia

Untuk mengonfigurasi Google sebagai penyedia identitas:

  1. Buka halaman Identity Provider di Konsol Google Cloud.

    Buka halaman Penyedia Identitas

  2. Klik Tambahkan Penyedia.

  3. Pilih Google dari daftar.

  4. Masukkan Client ID Web dan Web Secret Google Anda. Jika belum memiliki ID dan rahasia, Anda bisa mendapatkannya dari halaman API's & Services.

  5. Konfigurasikan URI yang tercantum di bagian Konfigurasikan Google sebagai URI pengalihan OAuth yang valid untuk aplikasi Google Anda. Jika Anda mengonfigurasi domain kustom di Identity Platform, perbarui URI pengalihan di konfigurasi aplikasi Google Anda agar menggunakan domain kustom, bukan domain default. Misalnya, ubah https://myproject.firebaseapp.com/__/auth/handler menjadi https://auth.myownpersonaldomain.com/__/auth/handler.

  6. Daftarkan domain aplikasi Anda dengan mengklik Add Domain di bagian Authorized Domains. Untuk tujuan pengembangan, localhost sudah diaktifkan secara default.

  7. Di bagian bawah Konfigurasi aplikasi Anda, klik Detail Penyiapan. Salin cuplikan tersebut ke kode aplikasi Anda untuk menginisialisasi Client SDK Identity Platform.

  8. Klik Save.

Memproses login pengguna dengan SDK Klien

  1. Buat instance objek penyedia Google:

    Web versi 9

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

    Web versi 8

    var provider = new firebase.auth.GoogleAuthProvider();
  1. Opsional: Tambahkan cakupan OAuth. Cakupan menentukan data yang Anda minta dari Google. Data yang lebih sensitif mungkin memerlukan cakupan tertentu. Baca dokumentasi penyedia untuk menentukan cakupan yang diperlukan aplikasi Anda.

    Web versi 9

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

    Web versi 8

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  1. Opsional: Lokalkan alur autentikasi. Anda dapat menentukan bahasa, atau menggunakan bahasa default perangkat:

    Web versi 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 versi 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  2. Opsional: Tentukan parameter OAuth kustom tambahan. Kunci ini khusus untuk Google, dan biasanya digunakan untuk menyesuaikan pengalaman autentikasi. Anda tidak dapat meneruskan parameter yang dicadangkan oleh OAuth atau Identity Platform.

Web versi 9

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

Web versi 8

provider.setCustomParameters({
  'login_hint': 'user@example.com'
});
  1. Gunakan objek penyedia Google untuk memproses login pengguna. Anda dapat membuka jendela pop-up, atau mengalihkan halaman saat ini. Pengalihan lebih mudah bagi pengguna di perangkat seluler.

    Untuk menampilkan pop-up, panggil signInWithPopup():

    Web versi 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 versi 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;
        // ...
      });

    Untuk mengalihkan halaman, panggil signInWithRedirect() terlebih dahulu.

    Ikuti praktik terbaik saat menggunakan signInWithRedirect, linkWithRedirect, atau reauthenticateWithRedirect.

    Web versi 9

    import { getAuth, signInWithRedirect } from "firebase/auth";
    
    const auth = getAuth();
    signInWithRedirect(auth, provider);

    Web versi 8

    firebase.auth().signInWithRedirect(provider);

    Kemudian, ambil token Google dengan memanggil getRedirectResult() saat halaman Anda dimuat:

    Web versi 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 versi 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;
        // ...
      });

Setelah memiliki token akses, Anda dapat menggunakannya untuk memanggil Google API. Contoh:

REST

curl -H "Authorization: Bearer [TOKEN]" https://www.googleapis.com/oauth2/v2/userinfo

Memproses login pengguna secara manual

Jika tidak ingin menggunakan Client SDK, Anda juga dapat menangani alur login secara manual:

  1. Integrasikan autentikasi Google ke dalam aplikasi Anda dengan mengikuti langkah-langkah dalam dokumentasi developer mereka.

  2. Buat pengguna login dengan Google menggunakan alur yang Anda terapkan di langkah sebelumnya.

  3. Tukarkan token yang Anda terima dari Google dengan kredensial Identity Platform:

    Web versi 9

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

    Web versi 8

    var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
  4. Gunakan kredensial untuk memproses login pengguna dengan Identity Platform:

    Web versi 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 versi 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;
        // ...
      });

Langkah selanjutnya