Signing in users with Google  |  Identity Platform Documentation  |  Google Cloud (2024)

  • Home
  • Technology areas
  • Identity Platform
  • Documentation
  • Guides
Stay organized with collections Save and categorize content based on your preferences.

This document shows you how to use Identity Platform to sign in users withGoogle.

Before you begin

This tutorial assumes you've already enabled Identity Platform, and have abasic web app written using HTML and JavaScript. See theQuickstart to learn how.

Configuring Google as a provider

To configure Google as an identity provider:

  1. Go to the Identity Providers page in the Google Cloud console.

    Go to the Identity Providers page

  2. Click Add A Provider.

  3. Select Google from the list.

  4. Enter your Google Web Client ID and Web Secret. Ifyou don't already have an ID and secret, you can obtain one from the page.

  5. Configure the URI listed under Configure Google as a valid OAuthredirect URI for your Google app. If you configured a custom domain in Identity Platform,update the redirect URI in your Google app configuration to use the custom domain insteadof the default domain. For example, change https://myproject.firebaseapp.com/__/auth/handler tohttps://auth.myownpersonaldomain.com/__/auth/handler.

  6. Register your app's domains by clicking Add Domain underAuthorized Domains. For development purposes, localhost is alreadyenabled by default.

  7. Under Configure your application, click Setup Details. Copy thesnippet into your app's code to initialize the Identity PlatformClient SDK.

  8. Click Save.

Signing in users with the Client SDK

  1. Create an instance of the Google provider object:

    Web version 9

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

    Web version 8

    var provider = new firebase.auth.GoogleAuthProvider();
  1. Optional: Add OAuth scopes. Scopes specify what data you arerequesting from Google. More sensitive data may require specificscopes. Consult the provider'sdocumentation to determine what scopes your app needs.

    Web version 9

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

    Web version 8

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  1. Optional: Localize the authentication flow. You can specify a language,or use the device's default language:

    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.// auth.useDeviceLanguage();

    Web version 8

    firebase.auth().languageCode = 'it';// To apply the default browser preference instead of explicitly setting it.// firebase.auth().useDeviceLanguage();
  2. Optional: Specify additional custom OAuth parameters. These arespecific to Google, and are typically used to customize theauthentication experience. You can't pass parameters reserved by OAuth or Identity Platform.

Web version 9

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

Web version 8

provider.setCustomParameters({ 'login_hint': 'user@example.com'});
  1. Use the Google provider object to sign in the user. You can eitheropen a pop-up window, or redirect the current page. Redirecting is easierfor users on mobile devices.

    To show a pop-up, call signInWithPopup():

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

    To redirect the page, first call signInWithRedirect().

    Follow the best practices when using signInWithRedirect, linkWithRedirect, or reauthenticateWithRedirect.

    Web version 9

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

    Web version 8

    firebase.auth().signInWithRedirect(provider);

    Then, retrieve the Google token by calling getRedirectResult()when your page loads:

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

Once you have an access token, you can use it to call the Google API.For example:

REST

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

Signing in users manually

If you don't want to use the Client SDK, you can also handle the sign-inflow manually:

  1. Integrate Google authentication into your app by following the stepsin their developer documentation.

  2. Sign in the user with Google using the flow you implemented in theprevious step.

  3. Exchange the token you receive from Google for anIdentity Platform credential:

    Web version 9

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

    Web version 8

    var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
  4. Use the credential to sign in the user with Identity Platform:

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

What's next

  • Learn more about Identity Platform users.
  • Sign in users with other identity providers.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-03-05 UTC.

Signing in users with Google  |  Identity Platform Documentation  |  Google Cloud (2024)
Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6403

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.