百度云认证签名生成
前言
使用百度云產(chǎn)品,文檔中,需要生成認(rèn)證簽名.
代碼
調(diào)用百度云接口,需要在headers中添加簽名(X-Bce-Signature字段)
以真人度查詢接口為例 (http://rtbasia.api.bdymkt.com/ipscore/query)
百度云生成認(rèn)證字符串文檔
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 + '
' + CanonicalURI + '
' + CanonicalQueryString + '
' + CanonicalHeaders;
CanonicalRequest = decodeURI(CanonicalRequest);
let signedHeaders = 'host'; // 可根據(jù)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;
}
總結(jié)
文檔中說headers中的字段都要參與簽名,其實大部分不需要,像本例中只需要host即可
如果生成的不對,可以對應(yīng)百度云的在線簽名生成工具的輸出結(jié)果進行比較,找到哪一步生成的不對即可
通常返回結(jié)果為空時,都是查詢出錯了。錯誤代碼一般都在返回的headers中,對照文檔的錯誤代碼即可找到錯誤原因。
百度云域名查詢大多數(shù)也查不到,建議域名查詢改用阿里云的。
原博客鏈接:https://www.cnblogs.com/xpengp/
總結(jié)
- 上一篇: SAP Fiori Elements遇到
- 下一篇: 一年一度的天琴座流星雨来啦,附观测小技巧