JavaScript Web Guide

User Authentication

Firebase makes authentication easy. It can integrate with your existing login server, or authenticate users with only client-side code. It has built-in functionality for email & password auth and third-party providers such as Facebook, Twitter, GitHub, and Google.

Overview

Most applications need to know the identity of a user. Knowing a user's identity allows an app to provide a customized experience and grant them permissions to access their data. The process of proving a user's identity is called authentication. Firebase provides a full set of authentication options out-of-the-box.

When a user authenticates to a Firebase app, three things happen:

  • Information about the user is returned in callbacks on the client device. This allows you to customize your app's user experience for that specific user.
  • The user information returned contains a uid (a unique ID), which is guaranteed to be distinct across all providers, and to never change for a specific authenticated user. The uid is a String that contains the name of the provider you're authenticating with, followed by a colon and a unique id returned from the provider.
  • The value of the auth variable in your app's Security and Firebase Rules becomes defined. This variable is null for unauthenticated users, but for authenticated users it is an object containing the user's unique (auth.uid) and potentially other data about the user. This allows you to securely control data access on a per-user basis.

Once a user authenticates to your app, Firebase manages their session, ensuring that the user is remembered across browser or application restarts.

Firebase apps have built-in support for logging in with email & password, social login providers such as Facebook, Google, Twitter, and GitHub, and single-session anonymous login. Apps that use Firebase's built-in auth services can handle user login entirely with client-side code, saving you time and the headache of operating your own backend.

If you have existing server-side authentication or single sign-on, you can also easily integrate it with Firebase. Download one of our helper libraries to generate authentication tokens on your own servers.

Simple Login Deprecated

Login is now a core feature of Firebase clients. Simple Login has been deprecated and documentation for this client is now available on Github.

Setup an Authentication Provider

Here is a list of the providers that Firebase applications support. Select the one that fits your needs, and follow the provider-specific steps to set it up.

Platform Description
Custom Generate your own login tokens. Use this to integrate with existing authentication systems. You can also use this to authenticate server-side workers.
Email & Password Let Firebase manage passwords for you. Register and authenticate users by email & password.
Anonymous Build user-centric functionality without requiring users to share their personal information. Anonymous authentication generates a unique identifier for each user that lasts as long as their session.
Facebook Authenticate users with Facebook by writing only client-side code.
Twitter Authenticate users with Twitter by writing only client-side code.
GitHub Authenticate users with GitHub by writing only client-side code.
Google Authenticate users with Google by writing only client-side code.

Configuring Login

For security reasons, if you're using a web-based OAuth flow (Facebook, Twitter, Github, or Google), only domains that you whitelist are allowed to initiate authentication for your app. This does not apply to Email & Password, Anonymous, or Custom authentication methods. All Firebase applications have localhost and 127.0.0.1 enabled by default for local development and testing. They also include https://<YOUR-FIREBASE-APP>.firebaseapp.com as an authorized origin in case you want to utilize Firebase Hosting. Add more authorized origins to enable authentication from domains where you host your app.

  1. Navigate to the App Dashboard for your application.
  2. Open the Login & Auth tab.
  3. Add all of the domains that host your app to the Authorized Domains field.

Enabling Providers

Next, you need to enable the provider for your Firebase app.

  1. Go to the Account Dashboard.
  2. Select your Firebase app.
  3. Choose the Login & Auth tab.
  4. Find the Authentication Providers section.
  5. Select a tab for a provider and enable authentication.
  6. If you're using a social login provider, like Facebook, copy your client ID and secret into the form.

The Firebase app is all set up for your provider. It's time to code.

Monitoring User Authentication State

Use the onAuth() method to listen for changes in user authentication state.

// Create a callback which logs the current auth state
function authDataCallback(authData) {
  if (authData) {
    console.log("User " + authData.uid + " is logged in with " + authData.provider);
  } else {
    console.log("User is logged out");
  }
}

// Register the callback to be fired every time auth state changes
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(authDataCallback);

To stop listening for changes, you can use offAuth().

ref.offAuth(authDataCallback);

Additionally, you can use the getAuth() method to synchronously check authentication state.

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
var authData = ref.getAuth();

if (authData) {
  console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
  console.log("User is logged out");
}

Persisting User Auth State

When a user authenticates, the default session length is 24 hours from initial authentication. This means that the user's authentication state will automatically be persisted between page loads. You can configure the session length by navigating to the Login & Auth section of your Firebase App Dashboard and configuring the Session Length dropdown on the top right. Every auth provider has an optional remember parameter.

If remember is set to default, the session will last for the time you've configured in your App Dashboard. You can set remember to sessionOnly to limit persistence to the lifetime of the current window. The session length will be the same across all authentication providers you're using. If you're using an onAuth() callback, it will be triggered when a user reloads a page as long as their session has not expired.

Logging Users In

The code to authenticate a user varies by provider and transport method, but they all have similar signatures and accept a callback function. Use it to handle errors and process the results of a successful login.

// Create a callback to handle the result of the authentication
function authHandler(error, authData) {
  if (error) {
    console.log("Login Failed!", error);
  } else {
    console.log("Authenticated successfully with payload:", authData);
  }
}

// Authenticate users with a custom authentication token
ref.authWithCustomToken("<token>", authHandler);

// Alternatively, authenticate users anonymously
ref.authAnonymously(authHandler);

// Or with an email/password combination
ref.authWithPassword({
  email    : 'bobtony@firebase.com',
  password : 'correcthorsebatterystaple'
}, authHandler);

// Or via popular OAuth providers ("facebook", "github", "google", or "twitter")
ref.authWithOAuthPopup("<provider>", authHandler);
ref.authWithOAuthRedirect("<provider>", authHandler);

Tokens issued to the authenticated users are valid for 24 hours by default. You can change this from the Login & Auth tab on the App Dashboard.

Note: Looking to authenticate connections in Node.js? Refer to the documentation for Firebase.authWithCustomToken().

Logging Users Out

Calling unauth() invalidates the user's token and logs them out of your application:

ref.unauth();

If you had previously used the onAuth() method to listen for authentication state, your callback would now be invoked with null for authData.

Storing User Data

Internally, Firebase apps generate JSON Web Tokens (JWTs) and create authenticated sessions by calling Firebase.loginWithCustomToken() with those tokens. Each user is assigned a uid (unique ID), a String which is guaranteed to be distinct across all providers, and to never change for a specific authenticated user.

Applications do not automatically store profile or user state. To persist user data you must save it to your database. The callback function will return an object containing the data for the authenticated user, which you can then write to your database.

In the code sample below, we authenticate the user, and then store user data in the path https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>, where users/ is any arbitrary path to store user data, and <uid> represents the unique id obtained from the authentication data.

This code saves a user's information after they authenticate, using the uid as the key for the user's profile.

// we would probably save a profile when we register new users on our site
// we could also read the profile to see if it's null
// here we will just simulate this with an isNewUser boolean
var isNewUser = true;

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
  if (authData && isNewUser) {
    // save the user's profile into the database so we can list users,
    // use them in Security and Firebase Rules, and show profiles
    ref.child("users").child(authData.uid).set({
      provider: authData.provider,
      name: getName(authData)
    });
  }
});

// find a suitable name based on the meta info given by each provider
function getName(authData) {
  switch(authData.provider) {
     case 'password':
       return authData.password.email.replace(/@.*/, '');
     case 'twitter':
       return authData.twitter.displayName;
     case 'facebook':
       return authData.facebook.displayName;
  }
}

When a user is saved using the above code, the /users/ node looks something like this:

{
  "users": {
    "simplelogin:213": {
      "provider": "password",
      "name": "bobtony"
    },
    "twitter:123": {
      "provider": "twitter",
      "name": "Andrew Lee"
    },
    "facebook:456": {
      "provider": "facebook",
      "name": "James Tamplin"
    }
  }
}

The uids are strings and by convention consist of the provider name followed by a colon and the id.

Dealing with Popups and Redirects

Firebase apps support three different ways to authenticate with OAuth providers - via pop-up, browser redirect, or credential login.

Third-party authentication methods use a browser pop-up window, or browser redirect, to prompt the user to sign-in, approve the application, and return the user's data to the requesting application.

Most modern browsers block pop-up windows unless they are invoked by direct user action. Therefore, we should only invoke the authWithOAuthPopup() method for third-party authentication upon the user's click.

Note: Browser popups and redirects are not available on all platforms or browser environments. Popups are not available in Chrome for iOS, iOS Preview Panes, or local, file:// URLs. Redirects are not available in PhoneGap / Cordova, or local, file:// URLs. Therefore, it is recommended that you use a combination of both authentication methods to cover all environments:

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");

// prefer pop-ups, so we don't navigate away from the page
ref.authWithOAuthPopup("google", function(error, authData) {
  if (error) {
    if (error.code === "TRANSPORT_UNAVAILABLE") {
      // fall-back to browser redirects, and pick up the session
      // automatically when we come back to the origin page
      ref.authWithOAuthRedirect("google", function(error) { /* ... */ });
    }
  } else if (authData) {
    // user authenticated with Firebase
  }
});

Handling Errors

When your app calls an authentication method, you pass it a callback. This function is invoked with the result of the authentication attempt, either an error or authData object.

All errors are Error objects containing at least code and message attributes. In some cases, additional information will be provided via the details attribute. For example:

{
  code: "TRANSPORT_UNAVAILABLE",
  message: "There are no login transports available for the requested method.",
  details: "More details about the specific error here."
}

In some cases you may want to explicitly check for specific errors to notify your user, or prompt them to login again. For example, if you're using email & password authentication, you would want to check for an invalid email or password:

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithPassword({
  email    : "bobtony@firebase.com",
  password : "invalid-password"
}, function(error, authData) {
  if (error) {
    switch (error.code) {
      case "INVALID_EMAIL":
        console.log("The specified user account email is invalid.");
        break;
      case "INVALID_PASSWORD":
        console.log("The specified user account password is incorrect.");
        break;
      case "INVALID_USER":
        console.log("The specified user account does not exist.");
        break;
      default:
        console.log("Error logging user in:", error);
    }
  } else {
    console.log("Authenticated successfully with payload:", authData);
  }
});

Authentication Sample App

Try it on JSFiddle

This interactive demo demonstrates registration and login. Once the user is logged in, we save that user information to a users location in our database and take them to a screen showing all the registered users in the system.

Full Error Listing

Error Code Description
AUTHENTICATION_DISABLED The requested authentication provider is disabled for this Firebase application.
EMAIL_TAKEN The new user account cannot be created because the specified email address is already in use.
INVALID_ARGUMENTS The specified credentials are malformed or incomplete. Please refer to the error message, error details, and Firebase documentation for the required arguments for authenticating with this provider.
INVALID_CONFIGURATION The requested authentication provider is misconfigured, and the request cannot complete. Please confirm that the provider's client ID and secret are correct in your App Dashboard and the app is properly set up on the provider's website.
INVALID_CREDENTIALS The specified authentication credentials are invalid. This may occur when credentials are malformed or expired.
INVALID_EMAIL The specified email is not a valid email.
INVALID_ORIGIN A security error occurred while processing the authentication request. The web origin for the request is not in your list of approved request origins. To approve this origin, visit the Login & Auth tab in your App Dashboard.
INVALID_PASSWORD The specified user account password is incorrect.
INVALID_PROVIDER The requested authentication provider does not exist. Please consult the Firebase Authentication documentation for a list of supported providers.
INVALID_TOKEN The specified authentication token is invalid. This can occur when the token is malformed, expired, or the Firebase app secret that was used to generate it has been revoked.
INVALID_USER The specified user account does not exist.
NETWORK_ERROR An error occurred while attempting to contact the authentication server.
PROVIDER_ERROR A third-party provider error occurred. Please refer to the error message and error details for more information.
TRANSPORT_UNAVAILABLE The requested login method is not available in the user's browser environment. Popups are not available in Chrome for iOS, iOS Preview Panes, or local, file:// URLs. Redirects are not available in PhoneGap / Cordova, or local, file:// URLs.
UNKNOWN_ERROR An unknown error occurred. Please refer to the error message and error details for more information.
USER_CANCELLED The current authentication request was cancelled by the user.
USER_DENIED The user did not authorize the application. This error can occur when the user has cancelled an OAuth authentication request.
  1. 1

    Next

    Installation & Setup

  2. 2

    Next

    Understanding Data

  3. 3

    Next

    Saving Data

  4. 4

    Next

    Retrieving Data

  5. 5

    Next

    Structuring Data

  6. 6

    Next

    Understanding Security

  7. 7

    Next

    User Authentication

  8. 8

    Next

    Offline Capabilities

  9. 9

    Next

    Deploying Your App