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. Untuk mempelajari cara mengaktifkan Identity Platform dan login, lihat Panduan memulai.
Mengonfigurasi Google sebagai penyedia
Untuk mengonfigurasi Google sebagai penyedia identitas:
- Buka halaman Penyedia Identitas di konsol Google Cloud .
- Klik Tambahkan Penyedia.
- Pilih Google dari daftar.
- Masukkan ID Klien Web dan Rahasia Web Google Anda. Jika Anda belum memiliki ID dan rahasia, Anda dapat memperolehnya dari halaman API & Layanan.
- Untuk mengizinkan akses dari client ID eksternal, klik Tambahkan, lalu tambahkan client ID Anda.
- Untuk mengonfigurasi layar izin, klik Konfigurasi layar. Halaman Google Auth Platform akan terbuka di tab terpisah.
- Di halaman Google Auth Platform, konfigurasi layar izin OAuth Anda.
-
Kembali ke halaman Identity providers, di panel samping Project settings, klik Add Domain, lalu tambahkan domain aplikasi Anda.
Sebaiknya jangan sertakan
localhost
dalam project produksi Anda. - Di bagian Konfigurasi aplikasi Anda, klik Detail Penyiapan. Salin cuplikan ke dalam kode aplikasi Anda untuk melakukan inisialisasi SDK klien Identity Platform.
- Klik Simpan.
Membuat pengguna login dengan SDK klien
-
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();
-
Opsional: Tambahkan cakupan OAuth. Cakupan menentukan data yang Anda minta dari Google. Data yang lebih sensitif mungkin memerlukan cakupan tertentu. Lihat
dokumentasi
penyedia untuk menentukan cakupan yang dibutuhkan 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');
-
Opsional: Melokalkan 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();
-
Opsional: Tentukan parameter OAuth kustom tambahan. Cookie 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' });
-
Gunakan objek penyedia Google untuk membuat pengguna login. 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
, ataureauthenticateWithRedirect
.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
Membuat pengguna login secara manual
Jika tidak ingin menggunakan SDK klien, Anda juga dapat menangani alur login secara manual:
- Integrasikan autentikasi Google ke dalam aplikasi Anda dengan mengikuti langkah-langkah dalam dokumentasi developer mereka.
- Login pengguna dengan Google menggunakan alur yang Anda terapkan di langkah sebelumnya.
-
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);
-
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 berikutnya
- Pelajari lebih lanjut pengguna Identity Platform.
- Membuat pengguna login dengan penyedia identitas lainnya.