百度智能云鉴权认证C#实现
概述
当您将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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构