授权 OAuth 1.0 与 Postman 一起工作,通过 Node.js 失败

Authorization OAuth 1.0 works with Postman, fails via Node.js

我正在尝试使用 HERE, the open API for maps and following their instructions here 授权我的应用程序我能够检索 accessToken。但是,当我尝试使用 Node.js' crypto 签署请求时,我得到的签名与 Postman 提供的签名不同。

这是来自 Postman 的 HTTP 代码片段:

POST /oauth2/token HTTP/1.1
Host: account.api.here.com
Authorization: OAuth oauth_consumer_key="apiKey",
    oauth_signature_method="HMAC-SHA256",
    oauth_timestamp="1591720243",
    oauth_nonce="X6Ukw2TWTBp",
    oauth_version="1.0",
    oauth_signature="rqXoIM8YOYpsLjcWZ5Yau15%2BDIwPHhj%2B7jk8xyAfpU4%3D"
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials

这是我的 Node.js 代码:

crypto = require('crypto'),
apiKey = 'apiKey',
url = 'https://account.api.here.com/oauth2/token',
sharedSecret = 'sharedSecret'

var reqObj = {
    oauth_consumer_key: apiKey,
    oauth_nonce: "X6Ukw2TWTBp",
    oauth_signature_method: "HMAC-SHA256",
    oauth_timestamp: "1591720243",
    oauth_version: "1.0"
};

var paramsStr = '';
for (var i in reqObj) {
  paramsStr += "&" + i + "=" + reqObj[i];
}

// had an extra '&' at the front
paramsStr = paramsStr.substr(1);

var sigBaseStr = "POST&" + encodeURIComponent(url) + "&" + encodeURIComponent(paramsStr);

// no access token but we still have to append '&' according to the instructions
sharedSecret += "&";

var hashedBaseStr  = crypto.createHmac('sha256', sharedSecret).update(sigBaseStr).digest('base64');
console.log(encodeURIComponent(hashedBaseStr));

以上代码输出如下:fWmRNPpjrbBkVBQiS8DhjTo6G%2B5Tpeb6PZAxNVo7sWc%3D。而从 Postman 的 header 可以看出签名是 rqXoIM8YOYpsLjcWZ5Yau15%2BDIwPHhj%2B7jk8xyAfpU4%3D.

我什至遵循了 this page 上的教程,但它返回的签名与我的代码完全相同,无法转换为有效请求。

有人可以指出问题出在我的代码中吗?我已经检查过 sigBaseStr 是否遵循 OAuth 1.0 规范中列出的请求,所以我不确定还有什么问题。

总而言之,我希望我的代码输出rqXoIM8YOYpsLjcWZ5Yau15%2BDIwPHhj%2B7jk8xyAfpU4%3D

非常感谢任何指导。

找出问题所在。

根据列出的示​​例 heregrant_type=client_credentials 对也必须是 reqObj.

的一部分

添加后,我就能匹配 Postman 和我的代码的签名。

正确代码如下:

crypto = require('crypto'),
apiKey = 'apiKey',
url = 'https://account.api.here.com/oauth2/token',
sharedSecret = 'sharedSecret'

var reqObj = {
    grant_type: "client_credentials", // <- new line
    oauth_consumer_key: apiKey,
    oauth_nonce: "X6Ukw2TWTBp",
    oauth_signature_method: "HMAC-SHA256",
    oauth_timestamp: "1591720243",
    oauth_version: "1.0"
};

var paramsStr = '';
for (var i in reqObj) {
  paramsStr += "&" + i + "=" + reqObj[i];
}

// had an extra '&' at the front
paramsStr = paramsStr.substr(1);

var sigBaseStr = "POST&" + encodeURIComponent(url) + "&" + encodeURIComponent(paramsStr);

// no access token but we still have to append '&' according to the instructions
sharedSecret += "&";

var hashedBaseStr  = crypto.createHmac('sha256', sharedSecret).update(sigBaseStr).digest('base64');
console.log(encodeURIComponent(hashedBaseStr));