In-app Chat
  • iOS
  • Android
  • Web
  • Flutter
  • React Native : JavaScript
  • Unity3D
  • Windows
  • macOS
  • Introduction
    • Overview
    • Basic concepts
  • Sample app
  • Getting started
  • Client SDKs
    • SDK downloads
    • Release notes
  • Guides
    • Users
    • Authentication
    • Manage users
    • Room
    • Group
    • Messaging
    • Call invitation (signaling)
    • Manage sessions
  • Offline push notifications
  • Error codes
  • Client APIs
  • Server APIs
  • Documentation
  • In-app Chat
  • Guides
  • Authentication

Authentication

Last updated:2023-11-03 15:04

To avoid unauthorized service access or operations, ZEGOCLOUD uses digital Tokens to control and validate users' room login privileges.


The validation process

Before you log in to a room, 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:

/Pics/ZIMChatRoom/en/tokenvalidation_EN.png

Generate a Token

Generate a Token on app server

For business security, you must generate Tokens on your app server.

To generate a Token, do the following:

  1. Go to the ZEGOCLOUD Admin Console to get the AppID and ServerSecret of your project.
  2. Use the token generator plug-in provided by ZEGOCLOUD to generate Tokens on your app server.
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:

var appId uint32 = <Your AppId>   // type: uint32
userId := <Your userID>  // type: string
secret := <ServerSecret>  // type: 32 byte length string
var effectiveTimeInSeconds int64 = <Your token effectiveTime> //type: int64; unit: s

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

Generate a Token using the browser

The following are the sample code for generating a Token using your browser:

A sample code is included below. However, this is strictly an example. We strongly recommend you generate the Token on your app server.

<!-- Import the crypto-js -->
<script src="./assets/js/crypto-js.min.js"></script>
var appConfig = {
    appID: 0, // The Token you get from your app server. 
    serverSecret: '', // The ServerSecret you get from in the ZEGOCLOUD admin console.
};

/**
 * Generates a Token
 *
 * Token = “04” + Base64.encode(expire_time + IV.length + IV + binary data/ciphertext.length + binary data/ciphertext)
 * Algorithm: AES<ServerSecret, IV>(token_json_str), mode: CBC/PKCS5Padding
 *
 * Here is the sample code to generate a Token on a client. We recommend you to generate the Token on your app server from leaking your ServerSecret.
 */
function generateToken(userID, seconds) {
    if (!userID) return '';

    // Construct the data to be encrypted
    var time = (Date.now() / 1000) | 0;
    var body = {
        app_id: appConfig.appID,
        user_id: userID,
        nonce: (Math.random() * 2147483647) | 0,
        ctime: time,
        expire: time + (seconds || 7200),
    };
    // Encrypt the body
    var key = CryptoJS.enc.Utf8.parse(appConfig.serverSecret);
    var iv = Math.random().toString().substr(2, 16);
    if (iv.length < 16) iv += iv.substr(0, 16 - iv.length);

    var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(body), key, { iv: CryptoJS.enc.Utf8.parse(iv) }).toString();
    var ciphert = Uint8Array.from(Array.from(atob(ciphertext)).map((val) => val.charCodeAt(0)));
    var len_ciphert = ciphert.length;

    // Create the Token.
    var uint8 = new Uint8Array(8 + 2 + 16 + 2 + len_ciphert);
    // expire: 8
    uint8.set([0, 0, 0, 0]);
    uint8.set(new Uint8Array(Int32Array.from([body.expire]).buffer).reverse(), 4);
    // iv length: 2
    uint8[8] = 16 >> 8;
    uint8[9] = 16 - (uint8[8] << 8);
    // iv: 16
    uint8.set(Uint8Array.from(Array.from(iv).map((val) => val.charCodeAt(0))), 10);
    // The length of the ciphertext: 2
    uint8[26] = len_ciphert >> 8;
    uint8[27] = len_ciphert - (uint8[26] << 8);
    // Ciphertext
    uint8.set(ciphert, 28);

    var token = `04${btoa(String.fromCharCode(...Array.from(uint8)))}`;
    console.log('generateToken', iv.length, body, token);

    return 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.

Use the Token

When logging in to a room, you need to pass the Token for validation. Otherwise, the login will fail.

var userInfo = { userID: '', userName: '' };
var token = ''; // The Token you get from your app server. 

zim.login(userInfo, token)
    .then(function() {
        // Login successful.
    })
    .catch(function(err) {
        // Login failed.
    });

Renew the Token

  • 30 seconds before a Token expires, the SDK sends out a notification through the tokenWillExpire callback. (If the period of validity of the Token is less than 30 seconds after a successful room login, the callback triggers immediately. )

  • 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.

// Set up and listen for the callback for Token expires. 
zim.on('tokenWillExpire', function(zim, second) {
    var token = ''; // Request a new Token from app server.
    zim.renewToken(token)    
        .then(function({ token }) {
            // Token renewed successfully.
        })
        .catch(function(err) {
            // Failed to renew the Token.
        });
})
Page Directory