百度云认证签名生成
前言
使用百度云产品,文档中,需要生成认证签名.
代码
- 调用百度云接口,需要在headers中添加签名(X-Bce-Signature字段)
- 以真人度查询接口为例 (http://rtbasia.api.bdymkt.com/ipscore/query)
- 百度云生成认证字符串文档
const apiUrl = `http://rtbasia.api.bdymkt.com/ipscore/query?ip=${ip}`;
const headers = {
'X-Bce-Signature': getAuthString(accessKeyId, AppSecret,'/ipscore/query', ip, 'rtbasia.api.bdymkt.com'),
'Host': 'rtbasia.api.bdymkt.com',
'ContentType': 'application/json'
};
function getAuthString(ak, sk, path, ip, host) {
// 1
const accessKeyId = ak;
const AppSecret = sk;
const timestamp = new Date().toISOString().replace(/\.\d*/, '');
// const timestamp = '2020-04-10T01:41:45Z';
const expirationPeriodInSeconds = 100;
let authStringPrefix = `bce-auth-v1/${accessKeyId}/${timestamp}/${expirationPeriodInSeconds}`;
// 2
let Method = 'POST';
let CanonicalURI = path;
let CanonicalQueryString = 'ip=' + ip;
let CanonicalHeaders = 'host:'+ host;
let CanonicalRequest = Method + '\n' + CanonicalURI + '\n' + CanonicalQueryString + '\n' + CanonicalHeaders;
CanonicalRequest = decodeURI(CanonicalRequest);
let signedHeaders = 'host'; // 可根据Header部分确定签名头域(signedHeaders)。签名头域是指签名算法中涉及到的HTTP头域列表。
// 3
let SigningKey = crypto
.createHmac('sha256', AppSecret) //你的secret
.update(authStringPrefix)
.digest()
.toString('hex');
// 4
let Signature = crypto
.createHmac('sha256', SigningKey) //你的secret
.update(CanonicalRequest)
.digest()
.toString('hex');
// 5
let authorization = `${authStringPrefix}/${signedHeaders}/${Signature}`;
// 打印变量 可对比 百度云在线签名生成 输出,找到错误
console.log('1', authStringPrefix);
console.log('2', CanonicalRequest);
console.log('3', SigningKey);
console.log('4', Signature);
console.log('5', authorization);
return authorization;
}
总结
原博客链接:https://www.cnblogs.com/xpengp/