Node.js 中的 OAuth1.0 标头 [英] OAuth1.0 header in Node.js

查看:31
本文介绍了Node.js 中的 OAuth1.0 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 API 通过使用 OAuth1.0 的邮递员,成功.现在我正在构建一个调用此 API 的 API,但是在尝试在 OAuth1.0 的 javascript 中设置等效项时遇到了问题.标题如下所示:

I've been using an API via postman that uses OAuth1.0, successfully. Now I'm building an API that calls this API but I'm having trouble when trying to set up the equivalent in javascript of the OAuth1.0. The header looks like this:

'Authorization': 'OAuth oauth_consumer_key="XXX",oauth_token="XXX",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1559312415",oauth_nonce="XXX",oauth_version="1.0",oauth_signature="XXX"'

我的问题与oauth_nonceoauth_signature 有关.我可以用来生成这两个参数的哈希函数是什么.
另外,我正在使用 AXIOS 请求.
感谢您抽出宝贵时间.

My problem is related to oauth_nonce and oauth_signature. What are the hash function that I can use to generate those 2 parameters.
Also, I'm using AXIOS for the request.
Thanks for your time.

推荐答案

我找到了 Axios 的解决方案.我创建了一个 OauthHelper 类来生成 Authorization 标头:

I was able to figure out a solution with Axios. I created an OauthHelper class to generate the Authorization header:

const crypto = require('crypto');
const oauth1a = require('oauth-1.0a');

const CONSUMERKEY = '<consumerKey>';
const CONSUMERSECRET = '<consumerSecret>';
const TOKENKEY = '<tokenKey>';
const TOKENSECRET = '<tokenSecret>';

class Oauth1Helper {
    static getAuthHeaderForRequest(request) {
        const oauth = oauth1a({
            consumer: { key: CONSUMERKEY, secret: CONSUMERSECRET },
            signature_method: 'HMAC-SHA1',
            hash_function(base_string, key) {
                return crypto
                    .createHmac('sha1', key)
                    .update(base_string)
                    .digest('base64')
            },
        })

        const authorization = oauth.authorize(request, {
            key: TOKENKEY,
            secret: TOKENSECRET,
        });

        return oauth.toHeader(authorization);
    }
}

module.exports = Oauth1Helper;

然后我就可以通过 Axios 从我需要的任何地方发布帖子:

Then I was just able to make the post from wherever I need via Axios:

const request = {
    url: 'https://api-domain.com',
    method: 'POST',
    body: {
        "uniqueId": 1234
    }
};

const authHeader = Oauth1Helper.getAuthHeaderForRequest(request);

return await axios.post(
    request.url,
    request.body,
    { headers: authHeader });

这篇关于Node.js 中的 OAuth1.0 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆