Google Authentication - Firebase

Created: 2015-11-10 15:02 Updated: 2015-11-10 15:02 Source: https://www.firebase.com/docs/web/guide/login/google.html Notebook: All Tech/Frontend Development

JavaScript Web Guide

Google Authentication

.

Configuring Your Application

To get started with Google authentication, you need to first create a new Google application. Click the Create Project button on that page and fill in a name and ID for your project. Once your application is created, navigate to APIs & authCredentials in the left-hand navigation menu, and select Create New Client ID.

Firebase requires web application access, so select Web application. Set Authorized JavaScript origins to https://auth.firebase.com. Finally, set the Authorized Redirect URI to https://auth.firebase.com/v2/<YOUR-FIREBASE-APP>/auth/google/callback. This allows Google's OAuth service to talk to the Firebase Authentication servers.

Make sure your application also has it's Product Name set on the APIs & authConsent Screen or Google will return a 401 error when authenticating.

After configuring your Google application, head on over to the Login & Auth section in your App Dashboard. Enable Google authentication and then copy your Google application credentials (Client ID and Client Secret) into the appropriate inputs. You can find your Google application's client ID and secret from the same APIs & authCredentials page you were just on. Look for them under the Client ID for web application header.

Logging Users In

If your user does not have an existing session, you can prompt the user to login and then invoke the Google login popup (e.g. after they have clicked a "Login" button) with the following snippet:

  1. var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
  2. ref.authWithOAuthPopup("google", function(error, authData) {
  3. if (error) {
  4. console.log("Login Failed!", error);
  5. } else {
  6. console.log("Authenticated successfully with payload:", authData);
  7. }
  8. });

Alternatively, you may prompt the user to login with a full browser redirect, and Firebase will automatically restore the session when you return to the originating page:

  1. var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
  2. ref.authWithOAuthRedirect("google", function(error) {
  3. if (error) {
  4. console.log("Login Failed!", error);
  5. } else {
  6. // We'll never get here, as the page will redirect on success.
  7. }
  8. });

Optional Settings

authWithOAuthPopup() and authWithOAuthRedirect() take an optional third parameter which is an object containing any of the following settings:

Name Description Type
remember If not specified - or set to default - sessions are persisted for as long as you have configured in the Login & Auth tab of your App Dashboard. To limit persistence to the lifetime of the current window, set this to sessionOnly. A value of none will not persist authentication data at all and will end authentication as soon as the page is closed. String
scope A comma-delimited list of requested extended permissions. See Google's documentation for more information. String

Here is an example of Google login where the session will expire upon browser shutdown and we also request the extended email permission:

  1. var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
  2. ref.authWithOAuthPopup("google", function(error, authData) { /* Your Code */ }, {
  3. remember: "sessionOnly",
  4. scope: "email"
  5. });

The authData object returned to your callback contains the following fields:

authData Object
Field Description Type
uid A unique user ID, intended as the user's unique key across all providers. String
provider The authentication method used, in this case: google. String
token The Firebase authentication token for this session. String
auth The contents of the authentication token, which will be available as the auth variable within your Security and Firebase Rules. Object
expires A timestamp, in seconds since the UNIX epoch, indicating when the authentication token expires. Number
google An object containing provider-specific data. Object
google.id The Google user's ID. String
google.accessToken The Google OAuth 2.0 access token granted by Google during user authentication. String
google.displayName The Google user's full name. String
google.email The Google user's primary email address as listed on their profile. Returned only if a valid email address is available, and the Google email permission was granted by the user. String
google.profileImageURL The URL of the Google user's profile picture. String
google.cachedUserProfile The Google user's raw profile, as specified by Google's user documentation. Note that the data included in this payload is generated by Google and may be changed by them at any time. Object

Security and Firebase Rules

Now that the client is logged in, your Security and Firebase Rules have access to their verified Google user ID. The auth variable contains the following values:

auth Variable
Field Description Type
uid A unique user ID, intended as the user's unique key across all providers. String
provider The authentication method used, in this case: google. String

Here is an example of how to use the auth variable in your Security and Firebase Rules:

  1. {
  2. "rules": {
  3. "users": {
  4. "$uid": {
  5. // grants write access to the owner of this user account whose uid must exactly match the key ($uid)
  6. ".write": "auth !== null && auth.uid === $uid",
  7. // grants read access to any user who is logged in with Google
  8. ".read": "auth !== null && auth.provider === 'google'"
  9. }
  10. }
  11. }
  12. }
See the User Authentication and User Based Security articles for more details.
.

View static HTML