Search code examples
javascriptwebrtctokbox

How to prevent usage of the same token to establish multiple connections to the WebRTC session when using TokBox/Vonage Video Api?


In our implementation of the WebRTC Video API of Tokbox/Vonage we need one user to be able to connect only once to the session at a time. We generate a unique token for each user on our platform, and they always use the same token to connect to any given session.

They way it works now, it is possible for the users to use different browsers or tabs or share their credentials to establish multiple connections to the session at the same time despite all the connections using the same token.

The consequences are worse when that person is publishing to the session. There are multiple video feeds of the user sent to everyone. Even if we handle it client side and show only one of those, the recordings still contain the duplicate and everyone's network bandwidth is wasted during the session.

Is there a way to end the previous connection from a token when a new one is established using it again? We need a token to be able to publish only 1 set of audio & video stream to a session at a time, and subscribe to others' streams on a single connection only.


Solution

  • The backend that generates the client token should have an option for overriding the expire_time. This controls when the token is no longer valid, and you should set this to as low a value as possible.

    For example, when generating a token in the PHP SDK you can pass an additional option to control that. Here we will expire it after 30 seconds:

    $now = new \DateTimeImmutable();
    $expire = $now->add(new \DateInterval('PT30S'));
    
    $clientToken = $opentok->generateToken($sessionId, [
        'expireTime' => $expire->toTimestamp()
    ]);
    

    You may want to use an even shorter time if you know the clients will get the token and connect fairly quickly. Sometimes a value as low as 5 seconds may work well, it just depends on latency and how quickly your client app uses a token after it asks for one.