Custom Token Authentication

Authenticate using a server generated JWT token

With Firebase, you can also authenticate using a custom token that's been generated on your server. It works like this:

  1. The user authenticates with your server

  2. The server generates a new authentication token based on the user's unique ID

  3. The token is passed back to the client and into the Chat SDK

Generating the token

To generate a token, you should follow the Firebase custom authentication guide.

Firebase also has an Admin SDK for Node.js, Java, Python and Go which makes the process more straightforward. you can install it using this guide.

In PHP, an implementation may look like this:

// Get your service account's email address and private key from the JSON key file
$service_account_email = "abc-123@a-b-c-123.iam.gserviceaccount.com";
$private_key = "-----BEGIN PRIVATE KEY-----...";

function create_custom_token($uid, $is_premium_account) {
  global $service_account_email, $private_key;

  $now_seconds = time();
  $payload = array(
    "iss" => $service_account_email,
    "sub" => $service_account_email,
    "aud" => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
    "iat" => $now_seconds,
    "exp" => $now_seconds+(60*60),  // Maximum expiration time is one hour
    "uid" => $uid,
    "claims" => array(
      "premium_account" => $is_premium_account
    )
  );
  return JWT::encode($payload, $private_key, "RS256");
}

The id should be the id your server uses to identify the user who is currently logged in. This token should be passed back to the app.

Authenticating on the client

AccountDetails details = new AccountDetails.token("Your token");
ChatSDK.auth().authenticate(details).subscribe(...);

Last updated