Voice Call
  • iOS
  • Android
  • Web
  • Flutter
  • React Native : JavaScript
  • Electron
  • Unity3D
  • Cocos Creator
  • Windows
  • macOS
  • Linux
  • Overview
  • Develop your app
    • Quick start
    • Enhance basic feature
      • Use Tokens for authentication
  • Upgrade using advanced features
    • Advanced features
      • Improve audio quality
        • Visualize the sound level
      • Message signaling
        • Broadcast real-time messages to a room
        • Quotas and limits
      • Play media files
        • Play media files
      • Mix the streams
  • Resources & Reference
    • SDK
    • Sample code
    • API reference
    • Debugging
    • FAQs
    • Key concepts
  • Documentation
  • Voice Call
  • Develop your app
  • Enhance basic feature
  • Use Tokens for authentication

Use Tokens for authentication

Last updated:2023-05-17 19:00

Introduction

To avoid unauthorized service access or operations, ZEGOCLOUD uses digital Tokens to verify user identity, control and validate user privileges. You will need to pass a Token when you log in to a room.

Currently, ZEGOCLOUD supports validating the following:

  • User identity: check users' identity by validating the Token.
  • User privileges:
    • Room login privilege: check users' privilege to log in to a room by validating the room ID contained in the Token.
    • Stream publishing privilege: check users' privilege to publish streams in a room by validating the ID of the published stream contained in the Token.

To improve business security, we recommend you enable the room login and stream publishing privilege validation for all scenarios. In particular:

  • In cases where your app provides different types of rooms dedicated to different users, such as general rooms and member-only rooms, it is necessary to validate a user's privilege to enter a room.
  • In a voice chat room, it is necessary to prevent users who are not on the speaker seats from speaking in the room.
  • In voice games such as Werewolf, it is necessary to prevent the scenario that when the app is hacked, the hacker can use different user IDs to log in to the same room to cheat in the game.

Prerequisites

Before you start to implement user privilege authentication in your app, make sure you complete the following steps:

  1. If you need the Room ID and Published stream ID authentication feature, contact ZEGOCLOUD Technical Support to enable it.

  2. Integrate the Video Call SDK and implement the basic video feature. For details, refer to Quick start.

Understand the process

Your app clients request Tokens from your app server and provide the Token for privilege validation when logging in to a room.

The following diagram shows the process of room login privilege validation:

  1. Your app client requests a Token from your app server.
  2. Your app server generates a Token and passes it to the client.
  3. Your app client logs in to a room with userID, roomID, and the Token.
  4. The ZEGOCLOUD SDK sends the Token to the ZEGO server for validation.
  5. The ZEGOCLOUD server returns the validation result to the ZEGO Express SDK.
  6. The ZEGOCLOUD SDK returns the validation result to the app client. If the validation passes, the user logs in to the room successfully; otherwise, the login fails.

Get the AppID and ServerSecret

Go to ZEGOCLOUD Admin Console to get the App ID and ServerSecret of your project.

After getting your AppID and ServerSecret, you can define the validation rules on your app server or client based on your business requirements.

Upon request from your app clients, your app server generates Tokens and sends the Tokens to the corresponding app clients.

ZEGOCLOUD provides an open-source Token generator plug-in on GitHub, which you can use to generate Tokens on your app server using different programming languages such as Go, C++, Java, Python, PHP,.NET, and Node.js.

Currently, the Token generator we provided supports generating the following two Tokens:

  • User identity Token: to check user identity, you can pass null to the payload field.
  • User privilege Token: to check user privileges by validating the room ID and the ID of the published stream, the payload field needs to be generated based on the following validation rules:
    • Validate room login privilege only: to check users' privilege to log in to a room, but not to check their privilege to publish streams in a room.
    • Validate stream publishing privilege only: to check users' privilege to publish streams in a room, but not to check their privilege to log in to a room.
    • Validate both room login and stream publishing privileges: to check users' privilege to log in to a room and also their privilege to publish streams in a room.
  • For business security, you must generate Tokens on your app server; Otherwise, there is a risk of ServerSecret being stolen.
  • For the ZEGO Express SDK 2.17.0 or later, use the token04 of the Token generator to generate a Token.
Language Supported version Core function Code base Sample code
User identity Token User privilege Token
Go
Go 1.14.15 or later
GenerateToken04
C++
C++ 11  or later
GenerateToken04
Java
Java 1.8  or later
generateToken04
Python
Python 3.6.8  or later
generate_token04
PHP
PHP 7.0  or later
generateToken04
.NET
.NET Framework 3.5  or later
GenerateToken04
Node.js
Node.js 8  or later
generateToken04

Take Go language as an example, you can do the following steps to generate a Token:

  1. go get github.com/ZEGOCLOUD/zego_server_assistant
  2. import "github.com/ZEGOCLOUD/zego_server_assistant/token/go/src/token04"
  3. Call the GenerateToken04 method to generate a Token.

The following code shows how to generate a user identity Token:

package main

import (
    "fmt"
    "github.com/ZEGOCLOUD/zego_server_assistant/token/go/src/token04"
)

/*
Sample code for generating a user identity Token: 
*/

func main() {
    var appId uint32 = 1
    userId := "demo"
    serverSecret := "fa94dd0f974cf2e293728a526b028271"
    var effectiveTimeInSeconds int64 = 3600
    var payload string = ""

    token, err := token04.GenerateToken04(appId, userId, serverSecret, effectiveTimeInSeconds, payload)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(token)
}

The following code shows how to generate a user privilege Token:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/ZEGOCLOUD/zego_server_assistant/token/go/src/token04"
)

/*
Sample code for generating a user privilege Token:
 */


//Token-based business logic: RTC room-related authentication property 
type RtcRoomPayLoad struct {
    RoomId       string      `json:"room_id"`           //Room ID: used to to validate the room.
    Privilege    map[int]int `json:"privilege"`         //User privilege authentication control list: used to validate user privileges 
    StreamIdList []string    `json:"stream_id_list"`    //Stream list: used to validate the stream. This value can be null, and no stream will be validated if it is null.
}

func main() {
    var appId uint32 = 1
    roomId := "demo"
    userId := "demo"
    serverSecret := "fa94dd0f974cf2e293728a526b028271"
    var effectiveTimeInSeconds int64 = 3600
    privilege := make(map[int]int)
    privilege[token04.PrivilegeKeyLogin] = token04.PrivilegeEnable
    privilege[token04.PrivilegeKeyPublish] = token04.PrivilegeEnable

    payloadData := &RtcRoomPayLoad{
        RoomId:       roomId,
        Privilege:    privilege,
        StreamIdList: nil,
    }

    payload, err := json.Marshal(payloadData)
    if err != nil {
        fmt.Println(err)
        return
    }

    token, err := token04.GenerateToken04(appId, userId, serverSecret, effectiveTimeInSeconds, string(payload))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(token)
}

How to get a temporary Token

To make it easier for you to try and test the user authentication feature, ZEGOCLOUD Admin Console provides a tool for generating temporary Tokens, which you can use directly in a testing environment. In production, you must generate Tokens on your app server.

Generate a Token on the client

If you can't generate the Token on your app server, you can try to generate it on your client.

When your app is ready to go live, remember not to generate the Token on your client; Otherwise, there is a risk of the ServerSecret being exposed.

ZEGOCLOUD provides an open-source Token generator plug-in on GitHub, which you can use to generate Tokens on your app server using different programming languages such as C++ and Java.

Language Supported version Core function Description
C++
C++ 11 or later
GenerateToken04
Java
Java 1.8 or later
generateToken04

Use a Token

When logging in to a room, you need to pass the Token, user, and roomID to the loginRoom method. Otherwise, the login will fail.

The userID you used for room login (loginRoom) must be the same with that of you used for generating Tokens.

let roomID = "xxx" // roomId to login
let user = {userID: "xxxx", userName: "xxxx"};
let roomConfig = {token: "xxxxxxxx"}; // Token from your app server
ZegoExpressEngine.instance().loginRoom(roomID, user, config);

If you need to modify the stream publishing privilege of a user after the user logged in to a room, call the renewToken method to renew the Token. The updated privileges will take effect for the next stream publishing, but will not affect the current streams being published (if any).

let token = getToken(); // Get a new token
ZegoExpressEngine.instance().renewToken(roomID, token);

Renew a Token

30 seconds before a Token expires, the SDK sends out a notification through the onRoomTokenWillExpire callback.

Upon receiving this callback, you need to get a new Token from your app server first, and then pass the new token to the renewToken method. If the Token is not renewed, different SDK versions handle the Token expiration differently:

  • If the version of the ZEGO Express SDK you integrated is 2.8.0 - 2.12.0, and when your Token is expired:

    • Users won't be kicked out of the room.
    • The streams currently being published will not be affected. However, it will affect the user's next stream publishing operation.
  • If the version of the ZEGO Express SDK you integrated is 2.13.0 or later, and when your Token is expired:

    • When the Token has expired, you can contact Technical Support for configuring additional privilege requirements. After configured:
      • Users will be kicked out of the room, and can't log in to the room again.
      • The streams currently being published will be stopped. And the next stream publishing operation can't be started.
    • When the Token has expired, and you didn't contact Technical Support for configuring additional privilege requirements:
      • Users won't be kicked out of the room.
      • The streams currently being published will not be affected. However, it will affect the user's next stream publishing operation.

If you enabled the room login privilege authentication (by validating the roomID), you must pass a new Token when logging in to a room.

ZegoExpressEngine.instance().on("roomTokenWillExpire", (roomID, remainTimeInSecond){
    let token = getToken(); // Get a new token
    ZegoExpressEngine.instance().renewToken(roomID, token);
});
Page Directory