5

I want to automate the OAuth 2.0 token automatically via javascript. Is there any way I can do that and obtain the token to use it in the artillery scrtips.

For the OAuth token generation I have below details:

  • Auth URL
  • Client ID
  • Scope

It is done by client authentication credentials.

Below is the sample code I am using to generate the token:

var ClientOAuth2 = require('client-oauth2')

var Auth = new ClientOAuth2({
  clientId: 'ClientID',
  accessTokenUri: 'https://Auth_URL/v2.0/token',
  authorizationUri: 'https://Auth_URL/v2.0/authorize',
  redirectUri: 'https://Auth_URL/',
  scope: 'api://Scope/access_as_user'
})




  Auth.owner.getToken('Username', 'password')
  .then(async (user) => {
    await console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  }).catch((e) => { console.log('error show',e); })
  .finally( () => console.log('end'));
QA_hacks
  • 257
  • 1
  • 6
  • 15

1 Answers1

2

You can declare your custom JS files which will be triggered every time before the request:

Your YAML file can be like here:

config:
  target: "https://baseUrl.com"
  phases:
    - duration: 60
      arrivalRate: 100
  processor: "./customFile.js"

scenarios:
  - flow:
      - post:
          url: "/pathInYourApi"
          headers:
            Content-Type: "application/json"
            Accept: application/json
          json: {}
          beforeRequest: "beforeRequest"

and then your customFile.js script:

module.exports = {
  beforeRequest: beforeRequest,
};

function beforeRequest(requestParams, context, ee, next) {
  // Call your OAuth client, and after you obtain token you can assign it to requestParams Authorization header
  // eg. requestParams.headers.Authorization = `Bearer + ${token}`

  return next(); // MUST be called for the scenario to continue
}
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
  • Thank you @BGladys for the quick reply. Can you also post any client code to generate the oauth 2.0 token please? Currently I am using NPM library "Client OAuth 2.0" for token generation but not able to generate the same. – QA_hacks Nov 05 '19 at 13:44
  • Check out if all the required params you've provided are correct: e.g from here: https://www.npmjs.com/package/client-oauth2 ` clientId: 'abc', clientSecret: '123', accessTokenUri: 'https://github.com/login/oauth/access_token', authorizationUri: 'https://github.com/login/oauth/authorize', redirectUri: 'http://example.com/auth/github/callback', scopes: ['notifications', 'gist'] ` – Bartłomiej Gładys Nov 05 '19 at 13:47
  • Yes, I am using the same format but not getting the token. All things are correct. Not sure what to give in "accessTokenUri:" field. Other than this all the correct info I am passing. Let me paste the same code with some mock details just to give you an idea – QA_hacks Nov 05 '19 at 14:10
  • I have update my question with the details of the code. Please check once – QA_hacks Nov 05 '19 at 14:14