阿里云认证签名生成
前言
使用阿里云产品,调用API接口一般有两种方式,使用APPCODE或使用ak、sk生成认证签名。
第二种比较复杂,今天记录一下。
代码
- 调用阿里云接口,需要在headers中添加签名(X-Ca-Signature字段)
- 以whois查询接口为例 (http://whois.market.alicloudapi.com/icredit_ai_seo/whois/v1)
- 阿里云生成认证字符串文档
- 以nodejs为例1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11const AppKey = 'your AK'; 
 const AppSecret = 'your SK';
 const domainName = 'your domain name';
 const apiUrl = `http://whois.market.alicloudapi.com/icredit_ai_seo/whois/v1?STRING=${domainName}`;
 const headers = {
 'Accept': 'application/json',
 'X-Ca-Key': AppKey,
 'X-Ca-Signature': getALYSignature(domainName, AppSecret, '/icredit_ai_seo/whois/v1')
 };1 
 2
 3
 4
 5
 6
 7
 8
 9// path 除根路径以外的其它部分 
 function getALYSignature(domainName, AppSecret, path) {
 let StringToSign = 'GET' + '\n' + 'application/json' + '\n' + '\n' + '\n' + '\n' + path + '?STRING=' + domainName;
 return crypto
 .createHmac('sha256', AppSecret)
 .update(StringToSign)
 .digest()
 .toString('base64'); // 这里使用base64 不是hex
 }
总结
- 使用阿里云的whois接口时,有的域名查询需要加**www.**才可以查询,有的不需要(规律我也找不到)。
- 通常返回结果为空时,都是查询出错了。错误代码一般都在返回的headers中,对照官方文档查看即可。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 个人记录!
 评论



