7

I'm trying to simulate webhook POST request to my Rails app (which works well in a real workflow) by Postman. I found lots of examples but none of them work - I keep getting a 401 code. What I did is defined headers and Pre-request Script like below:

postman headers

JS as Pre-request Script based on this docs

postman.setEnvironmentVariable("hmac", CryptoJS.HmacSHA256(request.data, 'my_secret_string').toString(CryptoJS.digest));

And still I'm getting the 401 error.

The external API docs which I use to trigger webhook clearly state:

Each webhook will be sent with the​ X-AQID-Signature​ header, which is created by hashing the request's payload with the HMAC method and SHA256 algorithm, using the shared secret as salt. This means that upon receiving a payload, you can verify its integrity by replicating the hashing method.

And like I said it works well in a real life workflow so I have an error in the postman implementation. What did I missed?

mr_muscle
  • 2,536
  • 18
  • 61
  • Did you see any errors? I think you do it right, the crypto part is not a problem, request payload might be. – lucas-nguyen-17 Jul 08 '21 at 23:16
  • @lucasnguyen17 except 401 I don't see any. My server logs shows me only `Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms | Allocations: 103)` and that's it. Payload (I mean body) probably shouldn't matter. – mr_muscle Jul 09 '21 at 00:07
  • 1
    sha256 produces same result with fixed inputs. So you can compare valid request with failed request to found out the differences. – lucas-nguyen-17 Jul 09 '21 at 02:08
  • @lucasnguyen17 exactly, so that's not the case - no difference what I put it there as long as it is a valid JSON. – mr_muscle Jul 09 '21 at 13:07

2 Answers2

10

You don't need to set any environment variable, you just have to add a header from your script. I did this in a very similar case:

var signBytes = CryptoJS.HmacSHA256(pm.request.body.raw, 'YOUR_SECRET');
var signHex = CryptoJS.enc.Hex.stringify(signBytes);
pm.request.headers.add({
    key: "HEADER_NAME",
    value: signHex
});
sinuhepop
  • 20,010
  • 17
  • 72
  • 107
5

If you need Base64 encoded value, then you can do it as follows:

CryptoJS.HmacSHA256(pm.request.body.raw, 'YOUR_SECRET').toString(CryptoJS.enc.Base64);
Gucu112
  • 877
  • 10
  • 12