鑒權(quán)代碼示例
本文為您介紹自定義鑒權(quán)URL相關(guān)功能使用,通過閱讀本文您可以了解如何進(jìn)行自定義鑒權(quán)URL以及如何對URL鑒權(quán)配置進(jìn)行更新。
鑒權(quán)URL生成
自定義鑒權(quán)URL
在您實(shí)際的業(yè)務(wù)中,您可能需要?jiǎng)討B(tài)生成推/播流URL,此時(shí)可以通過獲取鑒權(quán)配置進(jìn)行自定義拼接。接下來將通過Java SDK示例介紹如何實(shí)現(xiàn)動(dòng)態(tài)拼接推/播流URL。
在此之前如果您對URL鑒權(quán)地址結(jié)構(gòu)暫不了解,請參見鑒權(quán)URL組成。
由于鑒權(quán)URL需要根據(jù)鑒權(quán)KEY以及有效時(shí)長進(jìn)行加密,所以要?jiǎng)討B(tài)生成推/播流URL,需要先獲取到URL鑒權(quán)相關(guān)配置。
獲取URL鑒權(quán)配置需要調(diào)用DescribeLiveDomainConfigs查詢直播域名鑒權(quán)配置,具體示例代碼如下:
//需要將<>內(nèi)容替換成實(shí)際使用的值
DefaultProfile profile = DefaultProfile.getProfile("<regionId>", "<ALIBABA_CLOUD_ACCESS_KEY_ID>", "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>");
IAcsClient client = new DefaultAcsClient(profile);
DescribeLiveDomainConfigsRequest describeLiveDomainConfigsRequest=new DescribeLiveDomainConfigsRequest();
describeLiveDomainConfigsRequest.setDomainName("<DomainName>");
describeLiveDomainConfigsRequest.setFunctionNames("aliauth");
DescribeLiveDomainConfigsResponse describeLiveStreamSnapshotInfoResponse = null;
try {
describeLiveStreamSnapshotInfoResponse = client.getAcsResponse(describeLiveDomainConfigsRequest);
} catch (ClientException e) {
e.printStackTrace();
}
//鑒權(quán)key
String key="";
//有效時(shí)長(單位秒)
long expSeconds=0l;
for(DescribeLiveDomainConfigsResponse.DomainConfig.FunctionArg f:describeLiveStreamSnapshotInfoResponse.getDomainConfigs().get(0).getFunctionArgs()){
if("auth_key1".equals(f.getArgName())){
key=f.getArgValue();
}
if("ali_auth_delta".equals(f.getArgName())){
expSeconds=Long.valueOf(f.getArgValue());
}
}
System.out.println(key);
System.out.println(expSeconds);
獲取到鑒權(quán)KEY和有效時(shí)長后就可以對URL進(jìn)行拼接并加密,相關(guān)示例代碼請參考本文檔鑒權(quán)URL加密部分Java鑒權(quán)URL加密示例。
生成推流地址時(shí),要使用推流域名的鑒權(quán)KEY和有效時(shí)長。
生成播放地址時(shí),要使用播流域名的鑒權(quán)KEY和有效時(shí)長。
更新鑒權(quán)配置
在您實(shí)際的業(yè)務(wù)中,您的鑒權(quán)KEY可能是需要定期更換的,同時(shí)我們也建議您這樣做。此時(shí)可以通過調(diào)用BatchSetLiveDomainConfigs批量配置域名API進(jìn)行域名URL鑒權(quán)配置更新。
接下來將通過Java SDK示例代碼介紹如何更新URL鑒權(quán)配置。示例代碼如下:
//需要將<>內(nèi)容替換成實(shí)際使用的值
DefaultProfile profile = DefaultProfile.getProfile("<regionId>", "<ALIBABA_CLOUD_ACCESS_KEY_ID>", "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>");
IAcsClient client = new DefaultAcsClient(profile);
BatchSetLiveDomainConfigsRequest batchSetLiveDomainConfigsRequest =new BatchSetLiveDomainConfigsRequest();
batchSetLiveDomainConfigsRequest.setDomainNames("<DomainName>");
batchSetLiveDomainConfigsRequest.setFunctions("[{\"functionArgs\":[" +
"{\"argName\":\"auth_type\",\"argValue\":\"type_a\"}," +
"{\"argName\":\"auth_key1\",\"argValue\":\"<KEY_MAIN****>\"}," +
"{\"argName\":\"auth_key2\",\"argValue\":\"<KEY_BAK****>\"}," +
"{\"argName\":\"ali_auth_delta\",\"argValue\":<3600>}]," +
"\"functionName\":\"aliauth\"}]");
try {
BatchSetLiveDomainConfigsResponse response = client.getAcsResponse(batchSetLiveDomainConfigsRequest);
System.out.println(new Gson().toJson(response));
//todo something
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
該示例代碼實(shí)現(xiàn)了對<DomainName>的URL鑒權(quán)配置更新。鑒權(quán)類型為type_a(表示啟用鑒權(quán)),auth_key1(主KEY)為<KEY_MAIN****>,auth_key2(備KEY)為<KEY_BAK****>,ali_auth_delta(鑒權(quán)URL的有效時(shí)長)為<3600>秒,
主KEY或備KEY擁有同樣的效力,備KEY主要用于平滑更換。若主KEY執(zhí)行更換,所有使用主KEY生成的播放地址會(huì)立即失效。備KEY作為主KEY更換時(shí),使用主KEY的播放地址不會(huì)馬上中斷,備KEY可以繼續(xù)替代主KEY提供服務(wù),一般在更換時(shí)將舊的主KEY寫入備KEY。
鑒權(quán)URL加密
Java鑒權(quán)URL加密示例
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AuthDemo {
private static String md5Sum(String src) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
md5.update(StandardCharsets.UTF_8.encode(src));
return String.format("%032x", new BigInteger(1, md5.digest()));
}
private static String aAuth(String uri, String key, long exp) {
String pattern = "^(rtmp://)?([^/?]+)(/[^?]*)?(\\\\?.*)?$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(uri);
String scheme = "", host = "", path = "", args = "";
if (m.find()) {
scheme = m.group(1) == null ? "rtmp://" : m.group(1);
host = m.group(2) == null ? "" : m.group(2);
path = m.group(3) == null ? "/" : m.group(3);
args = m.group(4) == null ? "" : m.group(4);
} else {
System.out.println("NO MATCH");
}
String rand = "0"; // "0" by default, other value is ok
String uid = "0"; // "0" by default, other value is ok
String sString = String.format("%s-%s-%s-%s-%s", path, exp, rand, uid, key);
String hashValue = md5Sum(sString);
String authKey = String.format("%s-%s-%s-%s", exp, rand, uid, hashValue);
if (args.isEmpty()) {
return String.format("%s%s%s%s?auth_key=%s", scheme, host, path, args, authKey);
} else {
return String.format("%s%s%s%s&auth_key=%s", scheme, host, path, args, authKey);
}
}
public static void main(String[] args) {
String uri = "rtmp://example.aliyundoc.com/live/test****"; // original uri
String key = "<input private key>"; // private key of authorization
long exp = System.currentTimeMillis() / 1000 + 1 * 3600; // expiration time: 1 hour after current time
String authUri = aAuth(uri, key, exp);
System.out.printf("URL : %s\nAuth: %s", uri, authUri);
}
}
Python鑒權(quán)URL加密示例
import re
import time
import hashlib
import datetime
def md5sum(src):
m = hashlib.md5()
m.update(src)
return m.hexdigest()
def a_auth(uri, key, exp):
p = re.compile("^(rtmp://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
if not p:
return None
m = p.match(uri)
scheme, host, path, args = m.groups()
if not scheme: scheme = "rtmp://"
if not path: path = "/"
if not args: args = ""
rand = "0" # "0" by default, other value is ok
uid = "0" # "0" by default, other value is ok
sstring = "%s-%s-%s-%s-%s" %(path, exp, rand, uid, key)
hashvalue = md5sum(sstring.encode('utf-8'))
auth_key = "%s-%s-%s-%s" %(exp, rand, uid, hashvalue)
if args:
return "%s%s%s%s&auth_key=%s" %(scheme, host, path, args, auth_key)
else:
return "%s%s%s%s?auth_key=%s" %(scheme, host, path, args, auth_key)
def main():
uri = "rtmp://example.aliyundoc.com/test/test?vhost=demo.aliyundoc.liucom" # original uri
key = "<input private key>" # private key of authorization
exp = int(time.time()) + 1 * 3600 # expiration time: 1 hour after current itme
authuri = a_auth(uri, key, exp)
print("URL : %s\nAUTH: %s" %(uri, authuri))
if __name__ == "__main__":
main()
Go鑒權(quán)URL加密示例
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"regexp"
"time"
)
func md5sum(src string) string {
h := md5.New()
h.Write([]byte(src))
return hex.EncodeToString(h.Sum(nil))
}
func a_auth(uri, key string, exp int64) string {
p, err := regexp.Compile("^(rtmp://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
if err != nil {
fmt.Println(err)
return ""
}
m := p.FindStringSubmatch(uri)
var scheme, host, path, args string
if len(m) == 5 {
scheme, host, path, args = m[1], m[2], m[3], m[4]
} else {
scheme, host, path, args = "rtmp://", "", "/", ""
}
rand := "0" // "0" by default, other value is ok
uid := "0" // "0" by default, other value is ok
sstring := fmt.Sprintf("%s-%d-%s-%s-%s", path, exp, rand, uid, key)
hashvalue := md5sum(sstring)
auth_key := fmt.Sprintf("%d-%s-%s-%s", exp, rand, uid, hashvalue)
if len(args) != 0 {
return fmt.Sprintf("%s%s%s%s&auth_key=%s", scheme, host, path, args, auth_key)
} else {
return fmt.Sprintf("%s%s%s%s?auth_key=%s", scheme, host, path, args, auth_key)
}
}
func main() {
uri := "rtmp://example.aliyundoc.com/live/test****" // original uri
key := "<input private key>" // private key of authorization
exp := time.Now().Unix() + 3600 // expiration time: 1 hour after current itme
authuri := a_auth(uri, key, exp)
fmt.Printf("URL : %s\nAUTH: %s", uri, authuri)
}
PHP鑒權(quán)URL加密示例
<?php
function a_auth($uri, $key, $exp) {
preg_match("/^(rtmp:\/\/)?([^\/?]+)?(\/[^?]*)?(\\?.*)?$/", $uri, $matches);
$scheme = $matches[1];
$host = $matches[2];
$path = $matches[3];
$args = $matches[4];
if (empty($args)) {
$args ="";
}
if (empty($scheme)) {
$scheme ="rtmp://";
}
if (empty($path)) {
$path ="/";
}
$rand = "0";
// "0" by default, other value is ok
$uid = "0";
// "0" by default, other value is ok
$sstring = sprintf("%s-%u-%s-%s-%s", $path, $exp, $rand, $uid, $key);
$hashvalue = md5($sstring);
$auth_key = sprintf("%u-%s-%s-%s", $exp, $rand, $uid, $hashvalue);
if ($args) {
return sprintf("%s%s%s%s&auth_key=%s", $scheme, $host, $path, $args, $auth_key);
} else {
return sprintf("%s%s%s%s?auth_key=%s", $scheme, $host, $path, $args, $auth_key);
}
}
$uri = "rtmp://example.aliyundoc.com/live/test****";
$key = "<input private key>";
$exp = time() + 3600;
$authuri = a_auth($uri, $key, $exp);
echo "URL :" . $uri;
echo PHP_EOL;
echo "AUTH:" . $authuri;
?>
C#鑒權(quán)URL加密示例
using System;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
public class Test
{
public static void Main()
{
string uri= "rtmp://example.aliyundoc.com/live/test****"; // original uri
string key= "<input private key>"; // private key of authorization
DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
string exp = Convert.ToInt64((DateTime.Now - dateStart).TotalSeconds+3600).ToString(); // expiration time: 1 hour after current time
string authUri = aAuth(uri, key, exp);
Console.WriteLine (String.Format("URL :{0}",uri));
Console.WriteLine (String.Format("AUTH :{0}",authUri));
}
public static string aAuth(string uri, string key, string exp)
{
Regex regex = new Regex("^(rtmp://)?([^/?]+)(/[^?]*)?(\\\\?.*)?$");
Match m = regex.Match(uri);
string scheme = "rtmp://", host = "", path = "/", args = "";
if (m.Success)
{
scheme=m.Groups[1].Value;
host=m.Groups[2].Value;
path=m.Groups[3].Value;
args=m.Groups[4].Value;
}else{
Console.WriteLine ("NO MATCH");
}
string rand = "0"; // "0" by default, other value is ok
string uid = "0"; // "0" by default, other value is ok
string u = String.Format("{0}-{1}-{2}-{3}-{4}", path, exp, rand, uid, key);
string hashValue = Md5(u);
string authKey = String.Format("{0}-{1}-{2}-{3}", exp, rand, uid, hashValue);
if (args=="")
{
return String.Format("{0}{1}{2}{3}?auth_key={4}", scheme, host, path, args, authKey);
} else
{
return String.Format("{0}{1}{2}{3}&auth_key={4}", scheme, host, path, args, authKey);
}
}
public static string Md5(string value)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytes = Encoding.ASCII.GetBytes(value);
byte[] encoded = md5.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
for(int i=0; i<encoded.Length; ++i)
{
sb.Append(encoded[i].ToString("x2"));
}
return sb.ToString();
}
}
相關(guān)文檔
更多訪問控制功能說明,請參見開發(fā)指南訪問控制。
使用Java SDK,請參見Java SDK使用說明。