# Custom Token Authentication

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](https://firebase.google.com/docs/auth/admin/create-custom-tokens).

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](https://firebase.google.com/docs/admin/setup).

In PHP, an implementation may look like this:

```php
// 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**

{% tabs %}
{% tab title="Java" %}

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

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
BAccountDetails * details = [BAccountDetails token:@"Your token"];
[BChatSDK.auth authenticate: details].thenOnMain(...);
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chat-sdk.gitbook.io/chat-sdk/guides/custom-token-authentication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
