生成ARTC鉴权Token

本文将为您介绍如何生成启动通话所需的ARTC鉴权Token。

功能概述

AICallKit SDK提供的端侧接口可直接发起智能体通话,该接口需要传入一个鉴权Token。为此,您的业务服务器需要提供生成RTC鉴权Token的接口,以便您的客户端在调用前提前访问该接口获取Token。

生成步骤

生成ARTC Token时,您需获取音视频ARTC应用的AppIdAppKey。

  1. 前往智能媒体控制台,单击您创建好的智能体,进入智能体详情页面。

    image

  2. 单击RTC AppID,前往视频直播控制台,获取AppIdAppKey。

    image

  3. 根据获取的AppIdAppKey生成ARTC鉴权Token。Token的计算原理及方法如下,您可以根据如下方法计算Token。

    // 1. 拼接字段:AppID+AppKey+ChannelID+UserID+Nonce+Timestamp
    // 2. 使用sha256函数计算拼接字段,生成token。
    token = sha256(AppID+AppKey+ChannelId+UserID+Nonce+timestamp)
    //示例:
    AppID = "abc",AppKey="abckey",ChannelID="abcChannel",UserID="abcUser",Nonce="",Timestamp=1699423634
    token = sha256("abcabckeyabcChannelabcUser1699423634") = "3c9ee8d9f8734f0b7560ed8022a0590659113955819724fc9345ab8eedf84f31"

    参数名称

    描述

    AppID

    实时音视频应用ID和应用Key,在直播控制台创建实时音视频应用后会自动生成,详细请参见获取应用开发参数

    AppKey

    ChannelID

    频道ID,由用户自定义,String类型,不能使用Long类型,支持数字、大小写字母、短划线(-)、下划线(_),不超过64个字符。主播和连麦观众需使用同一个房间号。

    UserId

    用户ID,由用户自定义,String类型,不能使用Long类型,支持数字、大小写字母、短划线(-)、下划线(_),长度不超过64个字符。

    Nonce

    Nonce字符串可以为空,这里推荐为空

    Timestamp

    过期时间戳(秒级)。不能超过24小时,建议默认24小时。如果设置为24小时,则取当前秒数后再增加24*60*60。

    • 服务端生成Token:服务端生成Token示例代码如下:

      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);
          }
      }
      
      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': str(app_id),
                       'channelid': str(channel_id),
                       'userid':str(user_id),
                       'nonce':'',
                       'timestamp':timestamp,
                       'token':str(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()
      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)
      }
    • 客户端内置Token:如果您在开发阶段无法在AppServer上实现RTC Token的生成,可以选择在客户端本地进行签发。此方式要求在您的客户端内置RTC AppIdAppKey。生成客户端内置的Token时,您需要将Token及计算所需的五个参数(AppID、ChannelID、Nonce、UserIDTimestamp)生成为JSON格式后进行Base 64编码。随后,请将生成的Base 64 Token通过字符串形式传递至App侧,同时在App侧将Base 64 Token传送至ARTC SDK,并附加用于排查问题的UserName字段。

      重要

      该方法涉及内置的AppKey等敏感信息,仅适用于体验及开发阶段,不得用于线上发布,以防止AppKey被盗取而导致安全事件的发生。