Tous les produits
Search
Centre de documentation

ApsaraVideo Live:Token authentication

Dernière mise à jour :Aug 19, 2026

Les jetons sont des signatures de sécurité qui empêchent tout accès non autorisé à vos services cloud. Générez un jeton sur votre serveur et distribuez-le au SDK client, qui l'utilisera pour rejoindre un canal.

Prérequis

  • Vous disposez d'un compte Alibaba Cloud et le service ApsaraVideo Live est activé.

  • Vous avez créé une application ARTC et obtenu son AppID et sa AppKey. Pour plus d'informations, consultez la rubrique Créer une application ARTC.

Exemples de code

Génération côté serveur (recommandée)

Alibaba Cloud fournit des exemples de code pour Go, Java, Python et d'autres langages. Consultez les exemples de code de génération de jeton.

Génération côté client (pour le développement et le débogage uniquement)

Important

La génération d'un jeton nécessitant votre AppKey, l'intégrer dans votre code côté client présente un risque de sécurité majeur. Pour les applications en production, générez les jetons sur votre serveur d'application, puis distribuez-les au client.

Lors du développement et du débogage, si votre serveur d'application ne génère pas encore de jetons, vous pouvez temporairement en générer un côté client en suivant la logique APIExample. Exemple de code :

Générer un jeton sur un client Android : Android/ARTCExample/KeyCenter/src/main/java/com/aliyun/artc/api/keycenter/ARTCTokenHelper.java

Générer un jeton sur un client iOS : iOS/ARTCExample/Common/ARTCTokenHelper.swift

Rejoindre un canal avec un jeton

Remarque

Pour les applications en production, nous recommandons vivement de générer les jetons sur votre serveur d'application et de les distribuer au client afin de garantir la sécurité.

Utiliser un jeton pour rejoindre un canal sur un client Android : Android/ARTCExample/QuickStart/src/main/java/com/aliyun/artc/api/quickstart/TokenGenerate/TokenGenerateActivity.javaUtiliser un jeton pour rejoindre un canal sur un client iOS : iOS/ARTCExample/QuickStart/TokenGenerate/TokenGenerateVC.swift

Fonctionnement

Flux de travail du jeton

image
  1. Le client demande un jeton au serveur d'application. Le serveur d'application génère un jeton selon les règles requises et le renvoie.

  2. Le client utilise le jeton, l'AppID, l'ID de canal, l'ID utilisateur et d'autres informations pour rejoindre le canal spécifié.

  3. Le service ARTC d'Alibaba Cloud valide le jeton, ce qui permet au client de rejoindre le canal.

Génération de jeton

Le tableau suivant décrit les paramètres utilisés pour générer un jeton.

Paramètre

Description

AppID

L'ID et la clé de votre application ARTC, générés lors de la création d'une application ARTC dans la console ApsaraVideo Live. Consultez la rubrique Obtenir les paramètres de développement de l'application.

AppKey

ChannelId

Un ID de canal défini par l'utilisateur. La valeur doit être une chaîne et ne peut pas être de type Long. Elle peut contenir des chiffres, des lettres majuscules, des lettres minuscules, des traits d'union (-) et des underscores (_), et ne doit pas dépasser 64 caractères. L'hôte et les invités en co-diffusion doivent utiliser le même ID de canal.

UserID

Un ID utilisateur défini par l'utilisateur. La valeur doit être une chaîne et ne peut pas être de type Long. Elle peut contenir des chiffres, des lettres majuscules, des lettres minuscules, des traits d'union (-) et des underscores (_), et ne doit pas dépasser 64 caractères.

nonce

Le nonce peut être une chaîne vide. Nous recommandons de le laisser vide.

timestamp

L'horodatage d'expiration en secondes. Nous recommandons de définir l'expiration à 24 heures. Pour définir une expiration de 24 heures, ajoutez 86 400 (24 60 60) à l'horodatage actuel en secondes.

Exemple de processus de génération de jeton :

yuque_diagram (1)

Exemple de code de génération de jeton :

// 1. Concatenate the fields: AppID+AppKey+ChannelID+UserID+Nonce+Timestamp
// 2. Use the SHA-256 algorithm to hash the concatenated string and generate the token.
token = sha256(AppID+AppKey+ChannelId+UserID+Nonce+timestamp)
// Example:
AppID = "abc",AppKey="abckey",ChannelID="abcChannel",UserID="abcUser",Nonce="",Timestamp=1699423634
token = sha256("abcabckeyabcChannelabcUser1699423634") = "3c9ee8d9f8734f0b7560ed8022a0590659113955819724fc9345ab8eedf84f31"

Scénarios ARTC

Les exemples suivants montrent comment utiliser un jeton pour authentifier les utilisateurs rejoignant un canal dans un scénario ARTC sur Android et iOS.

Méthode à paramètre unique (recommandée)

Le SDK ARTC propose une API à paramètre unique pour rejoindre un canal. Cette approche évite les échecs de connexion au canal causés par des incohérences de paramètres entre votre serveur d'application et le client. Regroupez le jeton d'authentification, l'appid, le channelid, le nonce, l'userid et l'horodatage dans un objet JSON, puis encodez la chaîne JSON en Base64 pour créer une nouvelle chaîne d'authentification (jeton Base64).

Remarque

Lorsque vous contactez le support technique d'Alibaba Cloud, vous devez fournir le jeton Base64 ou le nom d'utilisateur que vous avez transmis.

yuque_diagram (3)

Exemple de génération de jeton Base64

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()

Node.js

'use strict'
const crypto = require('crypto')
function create_base64_token(appid, appkey, channelid, userid) {
    let timestamp = Math.floor(Date.now() / 1000 + 24 * 60 * 60)

    let string_builder = appid + appkey + channelid + userid + timestamp.toString()
    let token = crypto.createHash('sha256').update(string_builder).digest('hex')
    let base64tokenJson = {
        appid:appid,
        channelid:channelid,
        userid:userid,
        nonce:'',
        timestamp:timestamp,
        token:token
    }
    let base64token = Buffer.from(JSON.stringify(base64tokenJson), 'utf-8').toString('base64')
    return base64token
}

let appid = "your_appid";
let appkey = "your_appkey";
let channel_id = "your_channel_id";
let user_id = "your_user_id";

let base64token = create_base64_token(appid, appkey, channel_id, user_id)
console.log(base64token)

Rust

use chrono::{Duration, Utc};
use sha2::{Sha256, Digest};
use serde_json::json;
use base64::encode;

fn create_base64_token(appid: &str, appkey: &str, channel_id: &str, user_id: &str) -> String {
    // Calculate the expiration timestamp (24 hours from now)
    let timestamp = (Utc::now() + Duration::hours(24)).timestamp();

    // Concatenate the strings
    let string_builder = format!("{}{}{}{}{}", appid, appkey, channel_id, user_id, timestamp);

    // Calculate the SHA-256 hash
    let mut hasher = Sha256::new();
    hasher.update(string_builder);
    let token = hasher.finalize();
    let token_hex = format!("{:x}", token);

    // Create the JSON object
    let token_json = json!({
        "appid": appid,
        "channelid": channel_id,
        "userid": user_id,
        "nonce": "",
        "timestamp": timestamp,
        "token": token_hex
    });

    // Convert the JSON object to a string and encode it in Base64
    let base64_token = encode(token_json.to_string());

    base64_token
}

fn main() {
    let appid = "your_appid";
    let appkey = "your_appkey";
    let channel_id = "your_channel_id";
    let user_id = "your_user_id";

    let token = create_base64_token(appid, appkey, channel_id, user_id);
    println!("Base64 Token: {}", token);
}

Exemples d'appels d'API côté client

Une fois que le client a obtenu le jeton Base64 de votre serveur d'application, il utilise ce jeton pour rejoindre le canal.

  • Android :

    // You can set channelId and userId to null. If you pass values for channelId and userId, they must match those used to generate the token. You can use this feature to verify parameter consistency between the server and the client.
    // base64Token is the Base64-encoded token.
    // username is an identifier passed for troubleshooting purposes.
    mAliRtcEngine.joinChannel(base64Token, null, null, "username");
  • iOS :

    // You can set channelId and userId to null. If you pass values for channelId and userId, they must match those used to generate the token. You can use this feature to verify parameter consistency between the server and the client.
    // base64Token is the Base64-encoded token.
    // username is an identifier passed for troubleshooting purposes.
    [self.engine joinChannel:base64Token channelId:nil userId:nil name:@"username" onResultWithUserId:nil];

Méthode à plusieurs paramètres

Le SDK ARTC propose également une API à plusieurs paramètres pour rejoindre un canal. Cette méthode utilise la structure de données AliRtcAuthInfo pour stocker le jeton et les informations utilisateur destinées à l'authentification.

Important

L'ID de canal et l'ID utilisateur utilisés pour rejoindre le canal doivent correspondre à ceux utilisés pour générer le jeton.

  • Android :

    // Pass the token and user information for the multi-parameter method.
    AliRtcAuthInfo authInfo = new AliRtcAuthInfo();
    authInfo.appId = appId;
    authInfo.channelId = channelId;
    authInfo.userId = userId;
    authInfo.timestamp = timestamp;
    authInfo.nonce = nonce;
    authInfo.token = token;
    // Join the channel.
    mAliRtcEngine.joinChannel(authInfo, "");
  • iOS :

    // Pass the token and user information for the multi-parameter method.
    let authInfo = AliRtcAuthInfo()
    authInfo.appId = appId
    authInfo.channelId = channelId
    authInfo.nonce = nonce
    authInfo.userId = userId
    authInfo.timestamp = timestamp
    authInfo.token = authToken
    // Join the channel.
    self.rtcEngine?.joinChannel(authInfo, name: nil)

Scénarios de co-diffusion

Ajoutez les paramètres jeton, AppID, ChannelID, nonce, userId et horodatage à la chaîne query de l'URL de co-diffusion, puis transmettez l'URL au SDK. Pour plus de détails sur les champs de l'URL, consultez la rubrique Règles d'URL de co-diffusion.

image

Exemples d'URL

URL d'ingestion pour les scénarios de co-diffusion ou de battle :

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

URL de diffusion pour les scénarios de co-diffusion ou de battle :

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

live.aliyun.com est un préfixe fixe pour les URL de co-diffusion et n'est pas un vrai nom de domaine. N'effectuez aucune opération liée au domaine, telle que ping, traceroute ou telnet, sur cette adresse.

Gestion de l'expiration du jeton

Lorsque vous créez un jeton, le champ timestamp définit son heure d'expiration.

Après qu'un utilisateur a rejoint un canal à l'aide d'un jeton :

  • Le SDK déclenche le rappel onAuthInfoWillExpire 30 secondes avant l'expiration du jeton. Vous pouvez appeler la méthode refreshAuthInfo pour mettre à jour les informations d'authentification.

  • Lorsque le jeton expire, le SDK déclenche le rappel onAuthInfoExpired. Pour rester dans le canal, l'utilisateur doit le rejoindre à nouveau.