概述
当您将HTTP请求发送到百度智能云时,您需要对您的请求进行签名计算并生成认证字符串,以便百度智能云可以识别您的身份。您将使用百度智能云的访问密钥来进行签名计算,该访问密钥包含访问密钥ID(Access Key Id, 后文简称AK)和秘密访问密钥(Secret Access Key,).
生成公式
认证字符串的生成公式如下:
bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds }/{signedHeaders}/{signature}
主要包含了3部分,即前缀字符串(authStringPrefix)、签名头域(signedHeaders)和签名摘要(signature),其中:
前缀字符串:bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds }
,都是可获得的参数;
签名头域:即签名算法中涉及到的HTTP头域列表,将在下文中详细描述
签名摘要:为计算所得,将在下文中详细描述
以下使用c# BceSdkDotNetCore SDK实现
实现代码
public static class BceSignerHelper
{
public static string GetBceV1Signer(HttpMethod name,string url, Dictionary<string, string> prameters)
{
String accessKey = "xxx"; // 用户的Access Key ID
String secretKey = "xxx"; // 用户的Secret Access Key
// BceClientConfiguration
BceV1Signer bceV1Signer = new BceV1Signer();
var internalRequest = new InternalRequest();
internalRequest.HttpMethod = name.ToString();
internalRequest.Uri = new Uri(url);
internalRequest.Parameters = prameters;
List<string> list = new List<string> { "host" };
HashSet<string> hashSet = new HashSet<string>(list);
SignOptions signOptions = new SignOptions
{
HeadersToSign = hashSet
};
internalRequest.Headers = new Dictionary<string, string>()
{
{ "Host", "xxx" },
};
internalRequest.Config = new BceClientConfiguration
{
Credentials = new DefaultBceCredentials(accessKey, secretKey),
SignOptions = signOptions
};
return bceV1Signer.Sign(internalRequest);
}
}