Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

javascript - OAuth1.0 header in Node.js

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...