OAuth1.0 header in Node.js

£可爱£侵袭症+ 提交于 2020-07-06 22:56:49

问题


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"'

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.


回答1:


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;

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 });



回答2:


I was able to solve this issue, not by coding the hash funciont but by doing the request with Request as you can follow with this thread : How to call the API using OAuth 1.0?

The fact is I was using Axios and I wasn't finding a solution to how to make an OAuth1.0 with it. With Request, you can make it by using:

    request.get('https://api.twitter.com/1.1/users/show.json', {
  oauth:{
    consumer_key:'...',
    consumer_secret:'...',
    token:'...',
    token_secret:'...'
  }}, function (err, res, body) {})

as said by the post that I linked.



来源:https://stackoverflow.com/questions/56398985/oauth1-0-header-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!