Home > Net >  Generate oauth_signature and oauth_nonce from OAuth Key and secret
Generate oauth_signature and oauth_nonce from OAuth Key and secret

Time:08-10

I'm trying to request an API which use OAuth 1.0 protocol for authentification.

I have these informations :

OAuthKey (consumer key) : xxx
OAuthSecret : yyy

To perform my requests I need :

oauth_signature
oauth_nonce
oauth_timestamp

How to generate, with bash/python/js or anything, these data from the informations I have ?

CodePudding user response:

I wanted to do this with nodejs and axios.

So I used the informations in this post : OAuth1.0 header in Node.js

Create a OAuthHelper module :

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

const CONSUMERKEY = 'xxx';
const CONSUMERSECRET = 'yyy';

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

        return oauth.toHeader(authorization);
    }
}

module.exports = Oauth1Helper;

And my main code is :

const axios = require('axios');
const Oauth1Helper = require('./OauthHelper');

var request = {
    url: 'https://xxxx.com/rest/api...',
    method: 'GET'
};

var authHeader = Oauth1Helper.getAuthHeaderForRequest(request);


var config = {
  headers:{
    'custom_prop': 'custom_value',
    'authorization': authHeader.Authorization,
    'accept-language': 'fr-FR;q=1, en-FR;q=0.9'
  }
};

console.log(config);

axios.get(request.url, config)
  .then(res => {
    console.log('Status Code:', res.status);
    //...etc

  })
  .catch(err => {
    console.log('Error: ', err.message);
  });

I would prefer not to have a create a module to do that but I can't find a simple working solution for OAuth1 in nodejs with axios.

It works perfectly.

  • Related