/ SDKs / Flutter
SDKs
Chat SDKs Flutter v4
Chat SDKs Flutter
Chat SDKs
Flutter
Version 4

Authentication

Copy link

In order to use the features of the Chat SDK in your client apps, a SendbirdChat class should be initiated in each client app through user authentication with the Sendbird server. The instance communicates and interacts with the server based on the authenticated user account and is allowed to use the Chat SDK's features. This page explains how to authenticate your user with the server.


Initialize the Chat SDK with Application ID

Copy link

To use our chat features, you must initialize a SendbirdChat class by passing your Sendbird application's Application ID as an argument to a parameter of the init() method of SendbirdChat.

With the implementation of Local caching, you must determine whether you would like to use local caching and configure its settings through SendbirdChatOptions. The options contains properties such as useCollectionCaching. Set useCollectionCaching to true so that the SDK can use local cache for its collection instances. The default value of useCollectionCaching is true.

await SendbirdChat.init(
  appId: 'APP_ID',
  options: SendbirdChatOptions(useCollectionCaching: true),
);

Connect to the Sendbird server with a user ID

Copy link

By default, the Sendbird server authenticates a user with just a unique user ID. Then, the server queries the database to check for a match upon connection request. If no matching user ID is found, the server creates a new user account with a user ID. The user ID should be unique within a Sendbird application to be distinguishable from other identifiers such as a hashed email address or a phone number in your service.

While authenticating with just the user ID is convenient in the developing and testing stages of a service, a more secure authentication process using tokens is strongly recommended for most production environments.

Note: Go to the event handler page to learn more about the usages of the Chat SDK's handlers and callbacks.

// USER_ID below should be unique to your Sendbird application.
runZonedGuarded(() async {
  final user = await SendbirdChat.connect('USER_ID');
  // The user is connected to the Sendbird server.
}, (e, s) {
  // Handle error.
});

Note: Apart from initializing the SendbirdChat class, you should connect to the Sendbird server before calling almost every method through the Chat SDK. If you attempt to call a method without connecting, ConnectionRequiredException is returned.


Connect to the Sendbird server with a user ID and a token

Copy link

For a more secure way of authenticating a user, you can require authentication with either an access token or a session token along with a user ID.

Using an access token

Copy link

Using Chat Platform API, you can create a user with their own access token or issue an access token for an existing user. Once an access token is issued, a user is required to provide the access token when logging in to the Sendbird application.

  1. Using the Chat Platform API, create a Sendbird user account with information submitted when a user signs up or logs in to your service.

  2. Save the user ID along with the issued access token to your securely managed persistent storage.

  3. When the user attempts to log in to the application, load the user ID and access token from the storage, and then pass them to the connect() method.

  4. Periodically replacing the user's access token is recommended to protect the account.

Note: From Settings > Application > Security > Access token permission setting on your dashboard, you're able to prevent users without an access token from logging in to your Sendbird application or restrict their access to read and write messages.

// USER_ID below should be unique to your Sendbird application.
runZonedGuarded(() async {
  final user = await SendbirdChat.connect('USER_ID', accessToken: 'ACCESS_TOKEN');
  // The user is authenticated using the access token and is connected to the Sendbird server.
}, (e, s) {
  // Handle error.
});

Using a session token

Copy link

You can also use a session token instead of an access token to authenticate a user. Session tokens are a more secure option because they expire after a certain period whereas access tokens don't. See Chat Platform API guides for further explanation about the difference between access token and session token, how to issue a session token, and how to revoke all session tokens.


Set a session handler

Copy link

When a user is authenticated with a session token, the Chat SDK connects the user to the Sendbird server and can send data requests to the server for ten minutes as long as the session token hasn't expired or hasn't been revoked.

Upon the user's session expiration, the Chat SDK will refresh the session internally using the SessionHandler class. However, if the session token has expired or has been revoked, the Chat SDK can't do so. In that case, the client app needs to implement a SessionHandler instance to refresh the token and pass it back to the SDK so that it can refresh the session again.

Note: A SessionHandler instance must be set before the server connection is requested.

The following code shows how to implement the handler methods.

/// A handler required on refreshing the session key on expiration.
/// This should be added by [SendbirdChat.setSessionHandler] before the connection by [SendbirdChat.connect].
abstract class SessionHandler {
  /// App needs to fetch a new token and pass on the new token to SDK via [AccessTokenRequester.onSuccess],
  /// or [AccessTokenRequester.onFail] if error has occurred during the fetch.
  ///
  /// In case when app decides not to refresh the session for the user,
  /// they should call [AccessTokenRequester.onSuccess] with `null` as a token value.
  void onAccessTokenRequired(AccessTokenRequester accessTokenRequester);

  /// Called when:
  ///   1. The token has been revoked.
  ///   2. The app has returned `null` as a new token value on [AccessTokenRequester.onSuccess].
  ///
  /// SDK disconnects the connection before calling this callback by
  /// [SendbirdChat.disconnect], so the app is recommended to direct a user to a
  /// login page to connect again.
  void onSessionClosed();

  /// Called after SDK successfully refreshes the session key.
  void onSessionRefreshed() {}

  /// Called when the SDK runs into an error while refreshing the session key.
  void onSessionError(SendbirdException e) {}
}

Because SessionHandler is a base class used to notify any event regarding the user's session and session token, you can register more events through SendbirdChat.setSessionHandler(). See an example in the following code below.

class MySessionHandler extends SessionHandler {
  @override
  void onAccessTokenRequired(AccessTokenRequester accessTokenRequester) {}

  @override
  void onSessionClosed() {}

  @override
  void onSessionRefreshed() {}

  @override
  void onSessionError(SendbirdException e) {}
}

SendbirdChat.setSessionHandler(MySessionHandler());

Disconnect from the Sendbird server

Copy link

A user can be disconnected from the Sendbird server when they no longer need to receive messages. However, the user will still receive push notifications for new messages from group channels they've joined.

When disconnected, all event handlers in a user's client app registered by the addChannelHandler() or addConnectionHandler() method stop receiving event callbacks from the server. Then, all internally cached data in the client app, such as the channels that are cached when the getChannel() method of OpenChannel or GroupChannel is called, are also flushed.

Note: By default, most of the data related to users, channels, and messages are internally cached in the SendbirdChat of a user's client app, which are retrieved by the corresponding query instances or received through the event handlers.

try {
  await SendbirdChat.disconnect();
} catch (e) {
  // Handle error.
}