Node.js 中的 OAuth1.0 标头

编程入门 行业动态 更新时间:2024-10-22 17:20:07
本文介绍了Node.js 中的 OAuth1.0 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我一直在使用 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',
    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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 15:33:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/942672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!