Suggestions

close search

Connection Token Creation — Java

In order to authenticate a user connecting to an OpenTok session, a client must connect using a token (see this overview).

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

import com.opentok.OpenTok;
import com.opentok.exception.OpenTokException;

class Test {
    public static void main(String argv[]) throws OpenTokException {
        // Set the following constants to your OpenTok API key and API secret.
        // See https://tokbox.com/account/.
        OpenTok opentok = new OpenTok(API_KEY, API_SECRET);

        //Generate a basic session. Or you could use an existing session ID.
        String sessionId = opentok.createSession().getSessionId();

        String token = opentok.generateToken(sessionId);
        System.out.println(token);
    }
}

Calling the generateToken() method returns a string. This string is the token.

The following Java code example shows how to obtain a token that has a role of "publisher" and that has a connection metadata string:

import com.opentok.OpenTok;
import com.opentok.Role;
import com.opentok.TokenOptions;
import com.opentok.exception.OpenTokException;

class Test {
    public static void main(String argv[]) throws OpenTokException {
        // Set the following constants to your OpenTok API key and API secret.
        // See https://tokbox.com/account/.
        OpenTok opentok = new OpenTok(API_KEY, API_SECRET);

        //Generate a basic session. Or you could use an existing session ID.
        String sessionId = opentok.createSession().getSessionId();

        // Replace with meaningful metadata for the connection.
        String connectionMetadata = "username=Bob,userLevel=4";

        // Generate a token. Use the Role value appropriate for the user.
        TokenOptions tokenOpts = new TokenOptions.Builder()
          .role(Role.MODERATOR)
          .expireTime((System.currentTimeMillis() / 1000) + (7 * 24 * 60 * 60)) // in one week
          .data(connectionMetadata)
          .build());
        String token = opentok.generateToken(sessionId, tokenOpts);
        System.out.println(token);
    }
}

The method takes the following arguments: