Search code examples
javascriptoauth-2.0artillery

How to automate the OAuth 2.0 token generation using Artillery?


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

Solution

  • 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
    }