You're viewing the legacy docs. They are deprecated as of May 18, 2016.

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 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.

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.

Navigate to the App Dashboard for your application.

Open the Login & Auth tab.

Add all of the domains that host your app to the Authorized Domains field.

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.

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:

Since the user's uid property is unique, it is the recommended key for storing users.

Dealing with Popups and Redirects

Firefeed

For a robust example of authenticating users with Firebase in a production environment,
showcasing both third-party authentication as well as session persistence, see
the Firefeed repository on Github.

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:

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:

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.