当我尝试用oauth-1.0a
和node.js发送post请求时,nodejs中出现了这个奇怪的错误。
请求:
Headers:
Authorization: OAuth <...>
Accept: 'application/xml',
Content-Type: 'application/xml'
Body:
<account>
<firstName>${first}</firstName>
<lastName>${last}</lastName>
<email>${email}</email>
<urlRedirect>${redirecturl}</urlRedirect>
</account>`
响应:
401
An error occurred while trying to authenticate: Failed to validate signature.
代码:
require('dotenv').config()
const request = require('request')
const OAuth = require('oauth-1.0a')
const crypto = require('crypto')
var first = "real";
var last = "person";
var email = "real@person.com";
var redirecturl = "http://google.com"
const oauth = OAuth({
version: '1.0a',
consumer: {
key: process.env.CONSUMERKEY,
secret: process.env.CONSUMERSECRET,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
},
})
console.log(oauth)
const token = {
key: process.env.KEY,
secret: process.env.SECRET,
}
const request_data = {
url: `https://${process.env.CHURCHCODE}.fellowshiponeapi.com/v1/Accounts`,
method: 'POST',
data: `<account>
<firstName>${first}</firstName>
<lastName>${last}</lastName>
<email>${email}</email>
<urlRedirect>${redirecturl}</urlRedirect>
</account>`
}
const headers = Object.assign( oauth.toHeader(oauth.authorize(request_data, token)), {
Accept: 'application/xml',
'Content-Type': 'application/xml'
});
console.log(headers);
request(
{
url: request_data.url,
method: request_data.method,
headers: headers
},
function(error, response, body) {
console.log(response.statusCode)
console.log(response.statusMessage)
}
)
为什么会出现这种错误?
编辑:我使用的一个更有用的资源是:https://oauth.net/core/1.0/#signing_process但我还是想不通。
还应该提到的是,这个请求确实有效,就像在邮递员那里它成功地通过了一样。
您通常希望使用以下标头在请求中提供令牌:
Authorization: Bearer <token>
非
Authorization: OAuth <...>