xpengp

前言

使用百度云产品,文档中,需要生成认证签名.

代码

  1. 调用百度云接口,需要在headers中添加签名(X-Bce-Signature字段)
  2. 以真人度查询接口为例 (http://rtbasia.api.bdymkt.com/ipscore/query)
  3. 百度云生成认证字符串文档
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;
}

总结

  1. 文档中说headers中的字段都要参与签名,其实大部分不需要,像本例中只需要host即可
  2. 如果生成的不对,可以对应百度云的在线签名生成工具的输出结果进行比较,找到哪一步生成的不对即可
  3. 通常返回结果为空时,都是查询出错了。错误代码一般都在返回的headers中,对照文档的错误代码即可找到错误原因。
  4. 百度云域名查询大多数也查不到,建议域名查询改用阿里云的。

分类:

技术点:

相关文章: