Connection Token Creation

In order to authenticate a user connecting to a OpenTok session, a user's page must pass a token along with the API key. TokBox provides the developer with an API key when they sign up for the OpenTok API. The token uniquely identifies a client. To create a token use the generate_token() method of the OpenTok server-side libraries.

You can also use the Dashboard page to create tokens. This is particularly useful when testing an app. However, in a final production version of an app, you will want to use the generate_token() method of the OpenTok server-side libraries, not the Dashboard page, to generate tokens.

The following PHP code example shows how to generate a token using the OpenTok PHP server-side library:

<?PHP

require_once 'OpenTokSDK.php';

$a = new OpenTokSDK(API_Config::API_KEY,API_Config::API_SECRET);
print $a->generate_token('your_session_ID'); // Replace with the correct session ID
print "\n";

Calling the generate_token() method returns a string. This string is the token. You use server-side PHP code to include the token in the served web page.

Although the example illustrates use of the OpenTok PHP library, the other OpenTok server-side libraries (for Java, Python, and Ruby) work in much the same way. In each, you generate a token by calling the generate_token() method of the OpenTokSDK object. The method takes three arguments:

  • session_id (String) — The session ID corresponding to the session to which the user will connect.
  • role (String) — Optional. This defines the role the user will have. There are three roles: subscriber, publisher, and moderator. Subscribers can only subscribe to streams in the session (they cannot publish). Publishers can subscribe and publish streams to the session, and they can use the signaling API. Moderators have the privileges of publishers and, in addition, they can also force other users to disconnect from the session or to cease publishing. The default role (if no value is passed) is publisher.
  • connection_data (String) — Optional. A string containing metadata describing the connection. For example, you can pass the user ID, name, or other data describing the connection. You may obtain this data from a server-side database or from data provided to you by the client, depending on your application.
  • expire_time (int) — Optional. The time when the token will expire, defined as an integer value for a Unix timestamp (in seconds). If you do not specify this value, tokens expire in 24 hours after being created. The expire_time value, if specified, must be within 30 days of the creation time.

When you launch your site, use the OpenTok server-side library generate_token() method to obtain a unique token string for each user. For more details, see the OpenTok server-side libraries documentation.

Next workflow step: Initialize and connect to a session.

IRC Live Chat

Have a quick question? Chat with TokBox Support on IRC. Join chat