All Products
Search
Document Center

Intelligent Media Services:Token-based authentication

Last Updated:Jun 16, 2025

This topic describes the rules for generating tokens in ApsaraVideo Real-time Communication (ARTC) scenarios.

Prerequisites

  • An Alibaba Cloud account is created and ApsaraVideo Live is activated.

  • An ARTC application is created in the ApsaraVideo Live console. For more information, see Create an ARTC application.

  • The AppID and AppKey are obtained. For more information, see Query an AppKey.

What is token?

A token is a security credential that authenticates identities and protects your cloud services from malicious parties. When you call the joinChannel function of the SDK, you must specify the AppID, UserID, ChannelID, Nonce, Timestamp, and Token parameters. AppID specifies the ID of your application and UserID specifies the user ID. The token is calculated from a combination of AppID, AppKey, ChannelID, Nonce, UserID, and Timestamp. This mechanism prevents malicious parties from forging tokens to access your cloud services.

For easier integration, Alibaba Cloud provides different APIs for ARTC and co-streaming scenarios.

Token generation method

Use the following method to generate a token on the server side.

// 1. Concatenate the values of AppID, AppKey, ChannelID, UserID, Nonce, and Timestamp to form a string.
// 2. Hash the string by using SHA-256. The output is your token.
// 3. The following sample code provides an example on how to verify the hash algorithm:
// AppID="abc",AppKey="abckey",ChannelID="abcChannel",UserID="abcUser",Nonce="",timestamp=1699423634
// token = sha256("abcabckeyabcChannelabcUser1699423634") = "3c9ee8d9f8734f0b7560ed8022a0590659113955819724fc9345ab8eedf84f31"
// 4. Note: We recommend that you set Nonce to an empty string and set Timestamp to the current Unix timestamp incremented by 86,400 seconds (equivalent to 24 hours).
token = sha256(AppID+AppKey+ChannelId+UserID+Nonce+timestamp)

The following table describes the parameters used to generate the token.

Parameter

Description

AppID

The ID of the ARTC application. The ID is automatically generated when you create the ARTC application in the ApsaraVideo Live console. For more information, see Create an ARTC application.

AppKey

The credential of the ARTC application. For more information, see Query an AppKey.

channelID

The channel ID. It can be up to 64 characters in length and can contain digits, letters, hyphens (-), and underscores (_). The streamer and co-streamer need to use the same channel ID.

userId

The user ID. It can be up to 64 characters in length and can contain digits, letters, hyphens (-), and underscores (_).

nonce

We recommend that you set this parameter to an empty string.

timestamp

The timestamp that specifies when the token expires. The timestamp cannot be greater than 24 hours from the start of live streaming. We recommend that you set the timestamp to a value that adds 24 hours to the time when live streaming begins.

After the token is generated, the server can employ one of the following methods for further operations based on your business requirements:

  • Method 1 (single-parameter input): The server converts the token and its five input parameters (AppID, ChannelID, Nonce, UserID and Timestamp) into a JSON string, encodes the string in Base64, and sends the encoded string to the client application. The client then passes the Base64-encoded string to ARTC SDK, along with the UserName parameter that is used for troubleshooting purposes.

  • Method 2: The server constructs the URL for co-streaming by using the token and its five input parameters (AppID, ChannelID, Nonce, UserID, and Timestamp), and passes it to the co-streaming SDK.

image

Business scenarios

ARTC

In ARTC scenarios, you can use the single-parameter method. The single-parameter method serves as the syntactic sugar that helps prevent connection failures due to parameter mismatch between the server and the client.

If you use the single-parameter method, the server passes a Base64-encoded string to the client. To generate the Base64-encoded string, create a JSON object with the token, its five input parameters, and the gslb parameter, and then encode the JSON object in Base64. This method enables your app server and client application to communicate using a single parameter, which minimizes the risk of connection failures caused by data inconsistencies.

When you request technical support from Alibaba Cloud, you need to provide the Base64-encoded string or the UserName parameter.

Server-side sample code

Java

package com.example;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Calendar;
import org.json.JSONObject;

public class App {

    public static String createBase64Token(String appid, String appkey, String channelid, String userid) {
        // Calculate the expiration timestamp (24 hours from now)
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, 24);
        long timestamp = calendar.getTimeInMillis() / 1000;

        // Concatenate the strings
        String stringBuilder = appid + appkey + channelid + userid + timestamp;

        // Calculate the SHA-256 hash
        String token = sha256(stringBuilder);

        // Create the JSON object
        JSONObject base64tokenJson = new JSONObject();
        base64tokenJson.put("appid", appid);
        base64tokenJson.put("channelid", channelid);
        base64tokenJson.put("userid", userid);
        base64tokenJson.put("nonce", "");
        base64tokenJson.put("timestamp", timestamp);
        base64tokenJson.put("token", token);

        // Convert the JSON object to a string and encode it in Base64
        String jsonStr = base64tokenJson.toString();
        String base64token = Base64.getEncoder().encodeToString(jsonStr.getBytes(StandardCharsets.UTF_8));
        return base64token;
    }

    private static String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1)
                    hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String appid = "your_appid";
        String appkey = "your_appkey";
        String channel_id = "your_channel_id";
        String user_id = "your_user_id";

        String base64token = createBase64Token(appid, appkey, channel_id, user_id);
        System.out.println("Base64 Token: " + base64token);
    }
}

go

package main

import (
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"time"
)

func createBase64Token(appid, appkey, channelID, userID string) (string, error) {
	// Calculate the expiration timestamp (24 hours from now)
	timestamp := time.Now().Add(24 * time.Hour).Unix()

	// Concatenate the strings
	stringBuilder := appid + appkey + channelID + userID + fmt.Sprintf("%d", timestamp)

	// Calculate the SHA-256 hash
	hasher := sha256.New()
	hasher.Write([]byte(stringBuilder))
	token := hasher.Sum(nil)

	// Convert the hash to a hexadecimal string using encoding/hex
	tokenHex := hex.EncodeToString(token)

	// Create the JSON object
	tokenJSON := map[string]interface{}{
		"appid":     appid,
		"channelid": channelID,
		"userid":    userID,
		"nonce":     "",
		"timestamp": timestamp,
		"token":     tokenHex,
	}

	// Convert the JSON object to a string and encode it in Base64
	jsonBytes, err := json.Marshal(tokenJSON)
	if err != nil {
		return "", err
	}
	base64Token := base64.StdEncoding.EncodeToString(jsonBytes)

	return base64Token, nil
}

func main() {
	appid := "your_appid"
	appkey := "your_appkey"
	channelID := "your_channel_id"
	userID := "your_user_id"

	token, err := createBase64Token(appid, appkey, channelID, userID)
	if err != nil {
		fmt.Println("Error creating token:", err)
		return
	}
	fmt.Println("Base64 Token:", token)
}

Python

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import hashlib
import datetime
import time
import base64
import json

def create_base64_token(app_id, app_key, channel_id, user_id):
    expire = datetime.datetime.now() + datetime.timedelta(days=1)
    timestamp = int(time.mktime(expire.timetuple()))
    h = hashlib.sha256()
    h.update(str(app_id).encode('utf-8'))
    h.update(str(app_key).encode('utf-8'))
    h.update(str(channel_id).encode('utf-8'))
    h.update(str(user_id).encode('utf-8'))
    h.update(str(timestamp).encode('utf-8'))
    token = h.hexdigest()

    jsonToken = {'appid':app_id,
                 'channelid':channel_id,
                 'userid':user_id,
                 'nonce':'',
                 'timestamp':timestamp,
                 'token':token
                }
    base64Token = base64.b64encode(json.dumps(jsonToken).encode())

    return base64Token

def main():
    app_id = 'your_appid'
    app_key = 'your_appkey'
    channel_id = 'your_channel_id'
    user_id = 'your_user_id'

    base64Token = create_base64_token(app_id, app_key, channel_id, user_id)
    
    print(base64Token)

if __name__ == '__main__':
    main()

Client-side sample code

  • Java sample code for Android:

    // Set channelId and userId to null. If you assign other values to channelId and userId, make sure that these values match the values used to generate the token. You can implement a parameter consistency check between the server and client for verification.
    // base64Token is the Base64-encoded string.
    // username is an identifier used for troubleshooting purposes.
    mAliRtcEngine.joinChannel(base64Token, null, null, "username");
  • Objective-C sample code for iOS:

    // Set channelId and userId to null. If you assign other values to channelId and userId, make sure that these values match the values used to generate the token. You can implement a parameter consistency check between the server and client for verification.
    // base64Token is the Base64-encoded string.
    // username is an identifier used for troubleshooting purposes.
    [self.engine joinChannel:base64Token channelId:nil userId:nil name:@"username" onResultWithUserId:nil];

Co-streaming

  • In co-streaming or battle scenarios, the ingest and streaming URLs are in the following formats:

    Ingest URL:

    artc://live.aliyun.com/push/633?timestamp=1685094092&token=fe4e674ade****6686&userId=718&sdkAppId=xxx

    Streaming URL:

    artc://live.aliyun.com/play/633?timestamp=1685094092&token=fe4e674ade****6686&userId=718&sdkAppId=xxx
    Note

    live.aliyun.com is a fixed field in URLs for co-streaming. It is not a real domain name. Do not perform domain-related operations such as ping, traceroute, and telnet on it.