You can let your users authenticate with Firebase using their Google Accounts by
integrating Google Sign-In into your app. You can integrate Google Sign-In
either by using the Firebase SDK to carry out the sign-in flow, or by carrying
out the Google Sign-In flow manually and passing the resulting ID token to
Firebase.
On the Sign in method tab, enable the Google sign-in method
and click Save.
Handle the sign-in flow with the Firebase SDK
If you are building a web app, the easiest way to authenticate your users
with Firebase using their Google Accounts is to handle the sign-in flow with
the Firebase JavaScript SDK. (If you want to authenticate a user in Node.js
or other non-browser environment, you must handle the sign-in flow manually.)
To handle the sign-in flow with the Firebase JavaScript SDK, follow these
steps:
Create an instance of the Google provider object:
var provider = new firebase.auth.GoogleAuthProvider();
Optional: Specify additional OAuth 2.0 scopes that you
want to request from the authentication provider. To add a scope, call
addScope. For example:
Optional: Specify additional custom OAuth provider parameters
that you want to send with the OAuth request. To add a custom parameter, call
setCustomParameters on the initialized provider with an object containing the key
as specified by the OAuth provider documentation and the corresponding value. For example:
Authenticate with Firebase using the Google provider object. You can
prompt your users to sign in with their Google Accounts either by opening a
pop-up window or by redirecting to the sign-in page. The redirect method is
preferred on mobile devices.
To sign in with a pop-up window, call signInWithPopup:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(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;
// ...
});
Also notice that you can retrieve the Google provider's OAuth token which can be used to fetch additional data using the Google APIs.
This is also where you can catch and handle errors. For a list of error codes have a look at the Auth Reference Docs.
To sign in by redirecting to the sign-in page, call signInWithRedirect:
firebase.auth().signInWithRedirect(provider);
Then, you can also retrieve the Google provider's OAuth token by calling
getRedirectResult when your page loads:
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
}).catch(function(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;
// ...
});
This is also where you can catch and handle errors. For a list of error codes have a look at the Auth Reference Docs.
If you enabled the One account per email address setting in the Firebase console,
when a user tries to sign in a to a provider (such as Google) with an email that already
exists for another Firebase user's provider (such as Facebook), the error
auth/account-exists-with-different-credential is thrown along with an
AuthCredential object (Google ID token). To complete the sign in to the
intended provider, the user has to sign first to the existing provider (Facebook) and then link to the
former AuthCredential (Google ID token).
Popup mode
If you use signInWithPopup, you can handle
auth/account-exists-with-different-credential errors with code like the following
example:
// Step 1.
// User tries to sign in to Google.
auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()).catch(function(error) {
// An error happened.
if (error.code === 'auth/account-exists-with-different-credential') {
// Step 2.
// User's email already exists.
// The pending Google credential.
var pendingCred = error.credential;
// The provider account's email address.
var email = error.email;
// Get registered providers for this email.
auth.fetchProvidersForEmail(email).then(function(providers) {
// Step 3.
// If the user has several providers,
// the first provider in the list will be the "recommended" provider to use.
if (providers[0] === 'password') {
// Asks the user his password.
// In real scenario, you should handle this asynchronously.
var password = promptUserForPassword(); // TODO: implement promptUserForPassword.
auth.signInWithEmailAndPassword(email, password).then(function(user) {
// Step 4a.
return user.link(pendingCred);
}).then(function() {
// Google account successfully linked to the existing Firebase user.
goToApp();
});
return;
}
// All the other cases are external providers.
// Construct provider object for that provider.
// TODO: implement getProviderForProviderId.
var provider = getProviderForProviderId(providers[0]);
// At this point, you should let the user know that he already has an account
// but with a different provider, and let him validate the fact he wants to
// sign in with this provider.
// Sign in to provider. Note: browsers usually block popup triggered asynchronously,
// so in real scenario you should ask the user to click on a "continue" button
// that will trigger the signInWithPopup.
auth.signInWithPopup(provider).then(function(result) {
// Remember that the user may have signed in with an account that has a different email
// address than the first one. This can happen as Firebase doesn't control the provider's
// sign in flow and the user is free to login using whichever account he owns.
// Step 4b.
// Link to Google credential.
// As we have access to the pending credential, we can directly call the link method.
result.user.link(pendingCred).then(function() {
// Google account successfully linked to the existing Firebase user.
goToApp();
});
});
});
}
});
Redirect mode
This error is handled in a similar way in the redirect mode, with the difference that the pending
credential has to be cached between page redirects (for example, using session storage).
Advanced: Handle the sign-in flow manually
You can also authenticate with Firebase using a Google Account by handling
the sign-in flow with the Google Sign-In SDK:
Integrate Google Sign-In into your app by following the
integration guide.
Be sure to configure Google Sign-In with the Google Client ID generated for your Firebase project. You can find your project's Google Client ID in your Project's Developers Console Credentials page. Then replace:
<!-- **********************************************
* TODO(DEVELOPER): Use your Client ID below. *
********************************************** -->
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
<meta name="google-signin-cookiepolicy" content="single_host_origin">
<meta name="google-signin-scope" content="profile email">
After you integrate Google Sign-In, your web page has a Google Sign-In
button configured with a callback function, as in the following example:
In the sign-in button's result callback, exchange the ID token from the Google's auth response for a Firebase credential and sign-in Firebase:
function onSignIn(googleUser) {
console.log('Google Auth Response', googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
var unsubscribe = firebase.auth().onAuthStateChanged(function(firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(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;
// ...
});
} else {
console.log('User already signed-in Firebase.');
}
});
}
This is also where you can catch and handle errors. For a list of error codes have a look at the Auth Reference Docs.
Also you should check that the Google user is not already signed-in Firebase to avoid un-needed re-auth:
function isUserEqual(googleUser, firebaseUser) {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()) {
// We don't need to reauth the Firebase connection.
return true;
}
}
}
return false;
}
Advanced: Authenticate with Firebase in Node.js
To authenticate with Firebase in a Node.js application:
Sign in the user with their Google Account and get the user's Google ID
token. You can accomplish this in several ways. For example:
If your app has a browser front end, use Google Sign-In as described
in the Handle the
sign-in flow manually section. Get the Google ID token from the auth
response:
var id_token = googleUser.getAuthResponse().id_token
After you get the user's Google ID token, use it to build a Credential
object and then sign in the user with the credential:
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(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;
// ...
});
Next steps
After a user signs in for the first time, a new user account is created and
linked to the credentials—that is, the user name and password, or auth
provider information—the user signed in with. This new account is stored
as part of your Firebase project, and can be used to identify a user across
every app in your project, regardless of how the user signs in.
In your apps, the recommended way to know the auth status of your user is to
set an observer on the Auth object. You can then get the user's
basic profile information from the User object. See
Manage Users.
In your Firebase Realtime Database and Firebase Storage
Security Rules, you can
get the signed-in user's unique user ID from the auth variable,
and use it to control what data a user can access.