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

Custom Authentication

Firebase apps give you complete control over user authentication by allowing you to authenticate users using secure JSON Web Tokens (JWTs). This method of authentication is useful in cases where you are already managing user accounts on your server, where you have more advanced authentication needs, or for authenticating server-side workers.

Generating a Secure Token

To authenticate a user with Custom Login, we must provide each client with a secure JWT that has been generated on a server. There are several helper libraries for generating JWTs given a Firebase app's secret. Our secret can be found under the Secrets tab in our Firebase app's dashboard.

Firebase JWTs should always be generated on a trusted server so that the Firebase app secret which is needed to generate them can be kept private. Here are some examples of generating JWTs on a server using several different languages:

var FirebaseTokenGenerator = require("firebase-token-generator");
var tokenGenerator = new FirebaseTokenGenerator("<YOUR_FIREBASE_SECRET>");
var token = tokenGenerator.createToken({ uid: "uniqueId1", some: "arbitrary", data: "here" });
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("uid", "uniqueId1");
payload.put("some", "arbitrary");
payload.put("data", "here");

TokenGenerator tokenGenerator = new TokenGenerator("<YOUR_FIREBASE_SECRET>");
String token = tokenGenerator.createToken(payload);
var tokenGenerator = new Firebase.TokenGenerator("<YOUR_FIREBASE_SECRET>");
var authPayload = new Dictionary<string, object>()
{
  { "uid", "uniqueId1" },
  { "some", "arbitrary" },
  { "data", "here" }
};
string token = tokenGenerator.CreateToken(authPayload);
<?php
  include_once "FirebaseToken.php";

  $tokenGen = new Services_FirebaseTokenGenerator("<YOUR_FIREBASE_SECRET>");
  $token = $tokenGen->createToken(array("uid" => "uniqueId1"));
?>
from firebase_token_generator import create_token

auth_payload = { "uid": "uniqueId1", "auth_data": "foo", "other_auth_data": "bar" }
token = create_token("<YOUR_FIREBASE_SECRET>", auth_payload)
require "firebase_token_generator"

payload = { :uid => "uniqueId1", :auth_data => "foo", :other_auth_data => "bar" }

generator = Firebase::FirebaseTokenGenerator.new("<YOUR_FIREBASE_SECRET>")
token = generator.create_token(payload)

When authenticating with a secure JWT, the data encoded in the token will be accessible in the Security and Firebase Rules as the auth variable. This allows rules to be written which grant access based on the data within the token.

Token Restrictions

The token payload can contain any data of your choosing with the restriction that it must contain a uid key that is a string of less than 256 characters. The generated token's total payload must also be less than 1024 characters.

By default, authentication tokens expire 24 hours after they are issued and the client will automatically be unauthenticated at that time. You can override this by changing the session length setting under the Login & Auth tab of your App Dashboard, or individually when creating the token by providing a specific expiration date. For details, see the docs for the specific token generator library you're using.

To handle token expiration gracefully, we can use the addAuthStateListener() method, which triggers the provided callback whenever the authentication state changes.

Authenticating Clients

Once we've generated a secure JWT, we can use it to authenticate any Firebase database reference:

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
ref.authWithCustomToken(AUTH_TOKEN, function(error, authData) {
  if (error) {
    console.log("Login Failed!", error);
  } else {
    console.log("Login Succeeded!", authData);
  }
});
Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com/"];
[ref authWithCustomToken:AUTH_TOKEN withCompletionBlock:^(NSError *error, FAuthData *authData) {
    if (error) {
        NSLog(@"Login Failed! %@", error);
    } else {
        NSLog(@"Login succeeded! %@", authData);
    }
}];
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com/")
ref.authWithCustomToken(AUTH_TOKEN, withCompletionBlock: { error, authData in
    if error != nil {
        println("Login failed! \(error)")
    } else {
        println("Login succeeded! \(authData)")
    }
})
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
ref.authWithCustomToken(AUTH_TOKEN, new Firebase.AuthResultHandler() {
    @Override
    public void onAuthenticationError(FirebaseError error) {
        System.err.println("Login Failed! " + error.getMessage());
    }

    @Override
    public void onAuthenticated(AuthData authData) {
        System.out.println("Login Succeeded!");
    }
});

Calling an authentication method on any Firebase database reference will authenticate all references. If our app loses its Internet connection, Firebase clients will automatically handle re-authenticating to the server when it reconnects. If we need to change a client's credentials (for example, when a user logs in to a different account), simply re-authenticate with a new token.

It is not possible to authenticate with multiple credentials to the same Firebase database simultaneously, even if we call authWithCustomToken() on different references. Authentication state is global and applies to all references to the Firebase database. However, it is possible to create references to two or more different Firebase databases and authenticate to those independently.

authData Object
Field Description Type
auth The contents of the authentication token, which will be available as the auth variable within your Security and Firebase Rules. Map<String,Object>
expires A timestamp, in seconds since the UNIX epoch, indicating when the authentication token expires. Long
provider The authentication method used, in this case: custom. String
token The Firebase authentication token for this session. String
uid A unique user ID, intended as the user's unique key across all providers. String

To unauthenticate a client, use the unauth method:

ref.unauth();
[ref unauth];
ref.unauth()
ref.unauth();

Authenticating Servers

If we are running a trusted server that is connecting to our Firebase database, we can authenticate it in several ways:

  1. Using a Firebase app secret: All authentication methods can accept a Firebase app secret instead of a JWT token. This will grant the server complete read and write access to the entire Firebase database. This access will never expire unless it is revoked via the App Dashboard.
  2. Using a secure JWT with the optional admin claim set to true: This method will grant a server complete read and write access to the entire Firebase database. This token will expire normally, so it is important to set the expiration times accordingly.
  3. Using a secure JWT designed to give access to only the pieces of data a server needs to touch: This method is more complicated, but it is the safest way to authenticate a server as it lets the Security and Firebase Rules prevent the server from doing anything it's not supposed to, even if it becomes compromised in some way.

Generating a Token Without a Helper Library

Firebase app JWTs can also be generated with any existing JWT generation library and then signed by a SHA-256 HMAC signature. When using an existing library, a Firebase app auth token must contain the following claims:

Claim Description
v The version of the token. Set this to the number 0.
iat The "issued at" date as a number of seconds since the Unix epoch.
d The authentication data. This is the payload of the token that will become visible as the auth variable in the Security and Firebase Rules.

The following claims are optional when using an authentication token:

Claim Description
nbf The token "not before" date as a number of seconds since the Unix epoch. If specified, the token will not be considered valid until after this date.
exp The token expiration date as a number of seconds since the Unix epoch. If not specified, by default the token will expire 24 hours after the "issued at" date (iat).
admin Set to true to make this an "admin" token, which grants full read and write access to all data.
debug Set to true to enable debug mode, which provides verbose error messages when Security and Firebase Rules fail.

Helper Libraries

Language
Go (Unofficial)
Java
.NET
Node.js
Perl (Unofficial)
PHP
Python
Ruby
  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