'How to handle requests with signatures on karate tests?

First of all, thanks for build karate it's a very useful for test API's and UI's. We are using it to test a lot of our endpoints but we would like to know if there is a way or which is the best approach to handle requests with signature as part of the request in the header.

In our case we have two headers:

  • ApiKey: this value is always the same
  • Signature: this value depends on the request body content

Is there any way to inject the signature value just before the request is executed based on the request body content?

Here you can see two samples of the requests

Sample 1:

   * url 'https://dev.sample.com'
   * path '/api/user/getAll' 
   * header Content-Type = 'application/json'
   * header ApiKey = 'XXX' 
   * header Signature = 'YYY'
    And request {  }
    When method POST
    Then status 200    

Sample 2:

   * url 'https://dev.sample.com'
   * path '/api/user/getAll' 
   * header Content-Type = 'application/json'
   * header ApiKey = 'XXX' 
   * header Signature = 'ZZZ'
    And request { name: 'John' }
    When method POST
    Then status 200    

Thanks



Solution 1:[1]

Karate has a "hook" for generating headers, but as of now it is not "aware" of the currently built request body + headers: https://github.com/intuit/karate#configure-headers

We got a similar request here, and are thinking of adding this capability: How to retrieve raw request contents before making a REST call in Karate DSL?

Maybe the OAuth examples will give you the way forward for your case for now: https://stackoverflow.com/a/55055111/143475

Feel free to raise an enhancement request, and we can get this in to the next version (with your help to test it). I'm thinking - what if you are able to call karate.get('request') from within the header JS function.

But for now all you need to do is do something like this:

* def body = { some: 'json' }
* karate.set('requestBody', body)
* url someUrl
* request body
* method post

And in the header.js function

function fn() {
  var body = karate.get('requestBody');
  var sign = Utils.sign(body);
  return { Signature: sign };  
}

EDIT: this will be implemented in Karate 1.0 onwards: https://github.com/intuit/karate/issues/1385

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1