All Products
Search
Document Center

ApsaraVideo Live:Token-based authentication

Last Updated:Jul 15, 2024

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.

Background information

A token is a security credential in the form of a signature and is used to authenticate identities and protect 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 generated 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

You can 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 (multi-parameter input): The server sends the token and its five input parameters (AppID, ChannelID, Nonce, UserID, and Timestamp) in a JSON struct to the client side. The client then forwards these parameters to ARTC SDK and stores them locally. All parameters must be provided when you request technical support from Alibaba Cloud.

  • Method 2 (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 3: 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 choose between the single-parameter and multi-parameter methods. The single-parameter method serves as the syntactic sugar that helps prevent connection failures due to parameter mismatch between the server and the client. For ease of use, we recommend that you use the single-parameter method for ARTC scenarios.

Single-parameter input

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

Show Java sample code

/**
 * Generate a token by using the appid, appkey, channelId, userId, nonce, and timestamp parameters.
 *
 * @param appid     The application ID. You can view the ID on the details page of your application in the ApsaraVideo Live console. 
 * @param appkey    The AppKey. You can view the key on the details page of your application in the ApsaraVideo Live console. 
 * @param channelId The channel ID.
 * @param userId    The user ID.
 * @return token
 */
public static String createBase64Token(String appid, String appkey, String channelId, String userId) {
    /* Set the timestamp to no greater than 24 hours from the current time. */
    long timestamp = Calendar.getInstance().add(Calendar.HOUR_OF_DAY, 24).getTimeInMillis() / 1000;
    String stringBuilder = appid +
            appkey +
            channelId +
            userId +
            timestamp;
    String token = getSHA256(stringBuilder);
    JSONObject tokenJson = new JSONObject();
    tokenJson.put("appid", appid);
    tokenJson.put("channelid", channelId);
    tokenJson.put("userid", userId);
    tokenJson.put("nonce", "");
    tokenJson.put("timestamp", timestamp);
    tokenJson.put("gslb",new String[]{"https://gw.rtn.aliyuncs.com"});
    tokenJson.put("token", token);
    String base64Token = Base64.encodeToString(JSON.toJSONBytes(tokenJson),Base64.NO_WRAP);
	return base64Token;
}

/**
 * Obtain a signature.
 *
 * @param str The Base64-encoded string.
 * @return The signature that is returned.
 */
public static String getSHA256(String str) {
    MessageDigest messageDigest;
    String encodestr = "";
    try {
        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.getBytes("UTF-8"));
        encodestr = byte2Hex(messageDigest.digest());
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return encodestr;
}

private static String byte2Hex(byte[] bytes) {
    StringBuilder stringBuffer = new StringBuilder();
    String temp = null;
    for (byte aByte : bytes) {
        temp = Integer.toHexString(aByte & 0xFF);
        if (temp.length() == 1) {
            stringBuffer.append("0");
        }
        stringBuffer.append(temp);
    }
    return stringBuffer.toString();
}

Show Python sample code

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

import hashlib
import datetime
import time
import base64
import json

def create_token(app_id, app_key, channel_id, user_id, timestamp):
    h = hashlib.sha256()
    h.update(str(app_id))
    h.update(str(app_key))
    h.update(str(channel_id))
    h.update(str(user_id))
    h.update(str(timestamp))
    token = h.hexdigest()
    return token

def main():
    app_id = 'xxxxxx'
    app_key = 'xxxxxxxx'
    channel_id = 'abcChannel'
    user_id = 'abcUser1'
    expire = datetime.datetime.now() + datetime.timedelta(days=1)
    timestamp = int(time.mktime(expire.timetuple()))
    # timestamp = 1699423634
    token = create_token(app_id, app_key, channel_id, user_id, timestamp)
    print(token)
    jsonToken = {'appid':app_id,
                 'channelid':channel_id,
                 'userid':user_id,
                 'nonce':'',
                 'timestamp':timestamp,
                 'gslb':['https://gw.rtn.aliyuncs.com'],
                 'token':token
                }
    # String base64Token = Base64.encodeToString(JSON.toJSONBytes(tokenJson),Base64.NO_WRAP);
    print(json.dumps(jsonToken))
    base64Token = base64.b64encode(json.dumps(jsonToken).encode())
    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];

Multi-parameter input

If you use the multi-parameter method, the server sends the token and its input parameters to the client. The client parses these parameters into an AUTHINFO struct and calls ARTC SDK.

When you request technical support from Alibaba Cloud, you need to provide the AUTHINFO struct or the UserName parameter.

Server-side sample code

Show Java sample code

/**
 * Generate a token based on the appid, appkey, channelId, userId, nonce, and timestamp parameters.
 *
 * @param appid     The application ID. You can view the ID on the details page of your application in the ApsaraVideo Live console. 
 * @param appkey    The AppKey. You can view the key on the details page of your application in the ApsaraVideo Live console. 
 * @param channelId The channel ID.
 * @param userId    The user ID.
 * @param timestamp The expiration timestamp.
 * @return token
 */
public static String createToken(String appid, String appkey, String channelId, String userId) {
    /* Set the timestamp to no greater than 24 hours from the current time. */
    long timestamp = Calendar.getInstance().add(Calendar.HOUR_OF_DAY, 24).getTimeInMillis() / 1000;
    String stringBuilder = appid +
            appkey +
            channelId +
            userId +
            timestamp;
    return getSHA256(stringBuilder);
}

/**
 * Obtain a signature.
 *
 * @param str The Base64-encoded string.
 * @return The signature that is returned.
 */
public static String getSHA256(String str) {
    MessageDigest messageDigest;
    String encodestr = "";
    try {
        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.getBytes("UTF-8"));
        encodestr = byte2Hex(messageDigest.digest());
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return encodestr;
}

private static String byte2Hex(byte[] bytes) {
    StringBuilder stringBuffer = new StringBuilder();
    String temp = null;
    for (byte aByte : bytes) {
        temp = Integer.toHexString(aByte & 0xFF);
        if (temp.length() == 1) {
            stringBuffer.append("0");
        }
        stringBuffer.append(temp);
    }
    return stringBuffer.toString();
}

Client-side sample code

Show Java sample code for Android

// The values of appId, channelId, userId, nonce, timestamp, and token must be the same as the values on the server side.
// username is an identifier used for troubleshooting purposes.
AliRtcAuthInfo userInfo = new AliRtcAuthInfo();
userInfo.setAppId("xxx");
userInfo.setChannelId("xxx");
userInfo.setUserId("xxx");
userInfo.setNonce("xxx");
userInfo.setTimestamp(xxx);
userInfo.setGslb(new String[]{"https://gw.rtn.aliyuncs.com"});
userInfo.setToken("xxx");
mAliRtcEngine.joinChannel(userInfo, "username");

Show Objective-C sample code for iOS

// The values of appId, channelId, userId, nonce, timestamp, and token must be the same as the values on the server side.
// username is an identifier used for troubleshooting purposes.
AliRtcAuthInfo *authInfo = [[AliRtcAuthInfo alloc] init];
NSMutableArray *gslb = [[NSMutableArray alloc] init];
[gslb addObject:@"https://gw.rtn.aliyuncs.com"];
authInfo.appId = @"xxx";
authInfo.channelId   = @"xxx";
authInfo.userId   = @"xxx";
authInfo.nonce = @"";
authInfo.timestamp = xxxxx;
authInfo.gslb = gslb;
authInfo.token = @"";
[self.engine joinChannel:authInfo 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 telent, on it.