签名验证

最后更新时间:2021-09-22

介绍

为保证API及数据的安全,API调用仅支持HTTPS协议,且在调用API时,TB服务器会对每个API请求通过签名(Signature)进行身份验证。

对于每一个请求,TB服务器会根据请求头部的Authorization字段来校验是否合法。第三方须使用与TB服务端一致的签名算法才能通过验证,对于未包含签名字段或者签名错误的请求,函数计算将会返回HTTP 403错误。hmac-sha256:需要以您的AccessKey Secret为Key。

important

注意: 客户端需要保证生成的时间与TB服务端的时间相差不超过15分钟,否则将拒绝此次请求。

php样例

<?php
$params = [
'accessKeyId' => 'TbTestAccessKeyId',
'accessKeySecret' => 'TestSecret123456789',
'path' => 'open/third',
'contentType' => 'application/json',
'date' => gmdate("D, d M Y H:i:s") . " GMT"
];
//print_r(json_encode($params,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
echo PHP_EOL;
echo 'Authorization: '.calcSignature($params);
function calcSignature($p) {
$stringToSign = implode("\n", [$p['path'], $p['contentType'], $p['date']]);
$signature = base64_encode(hash_hmac('sha256', $stringToSign, $p['accessKeySecret'], true));
return 'TB '.$p['accessKeyId'].':'.$signature;
}

C#样例

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
public class Program
{
public void Main()
{
var para = new Dictionary<string, string>() {
{"accessKeyId", "TbTestAccessKeyId"},
{"accessKeySecret", "TestSecret123456789"},
{"path", "api/v1/xxx/xxx"},
{"contentType", "application/json"},
{"date", DateTime.UtcNow.ToString("r")}
};
string stringToSign = para["path"] + "\n" + para["contentType"] + "\n" + para["date"];
string sign = this.HmacSHA256ToBase64(stringToSign, para["accessKeySecret"]);
string auth = "Authorization: " + "TB " + para["accessKeyId"] + ":" + sign;
Console.WriteLine(auth);
}
public string HmacSHA256ToBase64(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
}

参数说明如下:

$path 格式为 /aaaa/bbbb 例如 open.baidu.com/open/third?appid=123456 中 /open/third

注意:增加在请求头信息中

Content-Type: 请求内容的类型,函数计算的类型是application/json

Date: 此次操作的时间,不能为空,时间格式为GMT。

样例

POST /xxxxx/xxxxx/xxxxx HTTP/1.1
Date: Thu, 16 Sep 2021 06:32:12 GMT
Authorization: TB LTAI5t7mtL4bduykzEaEmTGW:3wu0CdhTdkjRpHYsatPWcUznQVC8vcPRUZq1jdb/7Ys=
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 7