You're viewing the legacy docs. They are deprecated as of May 18, 2016.
These docs are for version 2.5.2 and below of the Java SDK. Go to our current docs, or see our Android migration guide.

Java Android 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, and third-party providers such as Facebook, Twitter, GitHub, and Google.


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.

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.

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 Authentication

To listen for changes in the authentication state, add an AuthStateListener.

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
    public void onAuthStateChanged(AuthData authData) {
        if (authData != null) {
            // user is logged in
        } else {
            // user is not logged in

You can also check the user's authentication state by calling the synchronous getAuth() function:

AuthData authData = ref.getAuth();
if (authData != null) {
  // user authenticated
} else {
  // no user authenticated

To stop listening to authentication state changes, you can use removeAuthEventListener().


Logging Users In

The code to authenticate a user varies by provider, but they all have a similar signature. They all accept an implementation of Firebase.AuthResultHandler. Use its callbacks to handle errors and process the results of a successful login.

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

// Create a handler to handle the result of the authentication
Firebase.AuthResultHandler authResultHandler = new Firebase.AuthResultHandler() {
    public void onAuthenticated(AuthData authData) {
        // Authenticated successfully with payload authData

    public void onAuthenticationError(FirebaseError firebaseError) {
        // Authenticated failed with error firebaseError

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

// Alternatively, authenticate users anonymously

// Or with an email/password combination
ref.authWithPassword("", "correcthorsebatterystaple", authResultHandler);

// Or via popular OAuth providers ("facebook", "github", "google", or "twitter")
ref.authWithOAuthToken("<provider>", "<oauth-token>", authResultHandler);

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

Logging Users Out

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


Storing User Data

Internally, Firebase generates JWT auth tokens and creates authenticated sessions by calling authWithOAuthToken() with those tokens. Each user is assigned a uid (a unique ID), which is guaranteed to be distinct across all providers, and to never change for a specific authenticated user.

When you authenticate a user, no profile or user state is stored in your Firebase database. If you would like this data to be persisted into the database you must do so explicitly. The AuthResultHandler will return an AuthData object. This AuthData object contains unique information about the logged in user.

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

final Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>");

ref.authWithPassword("", "correcthorsebatterystaple",
    new Firebase.AuthResultHandler() {

    public void onAuthenticated(AuthData authData) {
        // Authentication just completed successfully :)
        Map<String, String> map = new HashMap<String, String>();
        map.put("provider", authData.getProvider());
        if(authData.getProviderData().containsKey("displayName")) {
            map.put("displayName", authData.getProviderData().get("displayName").toString());


    public void onAuthenticationError(FirebaseError error) {
        // Something went wrong :(

A users node will be created in your database that looks something like this:

  "users": {
    "6d914336-d254-4fdb-8520-68b740e047e4": {
      "displayName": "alanisawesome",
      "provider": "password"
    "002a448c-30c0-4b87-a16b-f70dfebe3386": {
      "displayName": "gracehop",
      "provider": "password"

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

Handling Errors

When your app calls an authentication method, you pass it an implementation of AuthResultHandler. Its onAuthenticationError() method is called if there are any errors during the authentication process.

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:

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>");
ref.authWithPassword("", "correcthorsebatterystaple",
    new Firebase.AuthResultHandler() {
    public void onAuthenticated(AuthData authData) { /* ... */ }

    public void onAuthenticationError(FirebaseError error) {
        // Something went wrong :(
        switch (error.getCode()) {
            case FirebaseError.USER_DOES_NOT_EXIST:
                // handle a non existing user
            case FirebaseError.INVALID_PASSWORD:
                // handle an invalid password
                // handle other errors

Full Error Listing

Error Code Description
AUTHENTICATION_PROVIDER_DISABLED The requested authentication provider is disabled for this Firebase app. It can be enabled by going into the Login & Auth tab in your app dashboard.
EMAIL_TAKEN The new user account cannot be created because the specified email address is already in use.
INVALID_AUTH_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 application configuration.
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 `Authentication` 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 secret that was used to generate it has been revoked.
NETWORK_ERROR An error occurred while attempting to contact the authentication server.
PREEMPTED The current request was aborted by a new, incoming authentication request.
PROVIDER_ERROR A third-party provider error occurred. Please refer to the error message and error details for more information.
UNKNOWN_ERROR An unknown error occurred. Please refer to the error message and error details for more information.
USER_DENIED_AUTH The user did not authorize the application. This error can occur when the user has cancelled an OAuth authentication request.
USER_DOES_NOT_EXIST The specified user account does not exist.
  1. 1


    Installation & Setup

  2. 2


    Understanding Data

  3. 3


    Saving Data

  4. 4


    Retrieving Data

  5. 5


    Structuring Data

  6. 6


    Understanding Security

  7. 7


    User Authentication

  8. 8


    Offline Capabilities