Tokens & Authentication

Authentication vs Authorization

Stream uses JWT (JSON Web Tokens) to authenticate chat users, enabling them to login. Knowing whether a user is authorized to perform certain actions is managed separately via a role based permissions system.

The exception is Anonymous and Guest users who require no authentication to login.

Token Providers

A concept we will refer to throughout the docs is a Token Provider. At a high level, the Token Provider is an endpoint on your server that can perform the following sequence of tasks:

  1. Receive information about a user from the front end.

  2. Validate that user information against your system.

  3. Provide a User-ID corresponding to that user to the server client’s token creation method.

  4. Return that token to the front end.

User Tokens can only be safely generated from a server. This means you will need to implement a Token Provider prior to deploying your application to production. To conduct development before implementing a Token Provider, you will need to disable token authentication.

Generating Tokens

You can generate tokens on the server by creating a Server Client and then using the Create Token method.

If generating a token to use client side, the token must include the userID claim in the token payload, where as server tokens do not. When using the create token method, pass the user_ID parameter to generate a client-side token.

# pip install stream-chat
import stream_chat

server_client = stream_chat.StreamChat(
  api_key="{{ api_key }}", api_secret="{{ api_secret }}"
)
token = server_client.create_token("john")

Setting Automatic Token Expiration

By default, user tokens are valid indefinitely. You can set an expiration to tokens by passing it as the second parameter. The expiration should contain the number of seconds since Unix epoch (00:00:00 UTC on 1 January 1970).

// creates a token that expires in 1 hour using moment.js
const timestamp = Number(moment().add('1h').format('X'));
const token1 = client.createToken('john', timestamp);

// the same can be done with plain javascript
const token2 = client.createToken('john', Math.floor(Date.now() / 1000) + (60 * 60));

Manual Token Expiration

Token Revocation is a way to manually expire tokens for a single user or for many users by setting a revoke_tokens_issued_before time, and any tokens issued before this will be considered expired and will fail to authenticate. This can be reversed by setting the field to null.

Token Revocation by User

You can revoke all tokens that belong to certain user or list of users

await client.revokeUserToken("user-id", revokeDate);
await client.revokeUsersToken(["user1-id", "user2-id"], revokeDate);

Note: Your tokens must include the iat (issued at time) claim, which will be compared to the time in the revoke_tokens_issued_before field to determine whether the token is valid or expired. Tokens which have no iat will be considered valid.

Undoing the revoke

To undo user-level token revocation, you can simply set revocation date to null:

await client.revokeUserToken("user-id", null);
await client.revokeUsersToken(["user1-id", "user2-id"], null);

Token Revocation by Application

It is possible to revoke tokens for all users of an application. This should be used with caution as it will expire every user’s token, regardless of whether the token has an iat claim

await client.revokeTokens(revokeDate); 
// you can pass Date or ISOstring as value here

Undoing the revoke

To undo app-level token revocation, you can simply set revocation date to null:

await client.revokeTokens(null);

Adding iat claim to token

By default, user tokens generated through the createToken function do not contain information about time of issue. You can change that by passing the issue date as the third parameter while creating tokens. This is a security best practice, as it enables revoking tokens

client.createToken('user-id', expireTime, issuedAt);
// issuedAt should be unix timestamp
// issuedAt = Math.floor(Date.now() / 1000)

Developer Tokens

For development applications, it is possible to disable token authentication and use client-side generated tokens or a manually generated static token. Disabling auth checks is not suitable for a production application and should only be done for proofs-of-concept and applications in the early development stage. To enable development tokens, you need to change your application configuration.

On the Dashboard:

  1. Select the App you want to enable developer tokens on

  2. Click *App *name to enter the Chat Overview

  3. Scroll to the *Authentication *section

  4. Toggle Disable Auth Checks

  5. Click Save

This disables the authentication check, but does not remove the requirement to send a token. Send either a client generated development token, or manually create one and hard code it into your application.

val user = User(
  id = "bender",
  name = "Bender",
  image = "https://bit.ly/321RmWb",
)
val token = client.devToken(user.id)

client.connectUser(user, token).enqueue { /* ... */ }

The above code used the connectUser call. The connectUser call is the most convenient option when your app has authenticated users. Alternatively, you can use setGuestUser if you want to allow users to chat with a guest account or the connectAnonymousUser if you want to allow anonymous users to watch the chat.

Manually Generating Tokens

You can generate a token manually using the JWT generator.

If you need to test your app before you have a Token Provider and you don’t want to enable developer tokens, you can hardcode tokens from this generator into your app for testing.

How to Refresh Expired Tokens

If you’re using tokens with an expiration date you’ll want to update tokens as soon as a token exception occurs. Our React, RN, iOS, Android and Flutter libraries have built-in support for this.

Here is the regular flow to handle tokens with expiration with a token provider:

  1. Chat is initialized using the API Key and the token provider

  2. The Chat client will use the token provider to fetch the token when connectUser is called

  3. When the token expires, the API will return a specific Authentication error code

  4. The client will pause API requests and use the token provider to obtain a fresh token

  5. The token provider returns a new token (ie. from your backend)

  6. Chat client replaces the old token with the new one and use it for all waiting and future API calls

A token provider is a function or class that you implement and that is responsible for requesting a new token from your own login infrastructure.

The most common token provider implementation does an HTTP call to your backend with the ID of the user as well as a valid session id or secret needed to authenticate them.

val user = User(
  id = "bender",
  name = "Bender",
  image = "https://bit.ly/321RmWb",
)

val tokenProvider = object : TokenProvider {
  // Make a request to your backend to generate a valid token for the user
  override fun loadToken(): String = yourTokenService.getToken(user)
}
client.connectUser(user, tokenProvider).enqueue { /* ... */ }
© Getstream.io, Inc. All Rights Reserved.