HMAC - SHA256 authentication via Postman
Asked Answered
U

2

11

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?

Unblessed answered 8/7, 2021 at 16:13 Comment(4)
Did you see any errors? I think you do it right, the crypto part is not a problem, request payload might be.Wellesz
@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.Unblessed
sha256 produces same result with fixed inputs. So you can compare valid request with failed request to found out the differences.Wellesz
@lucasnguyen17 exactly, so that's not the case - no difference what I put it there as long as it is a valid JSON.Unblessed
K
13

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
});
Karlakarlan answered 2/6, 2022 at 11:24 Comment(0)
A
10

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);
Amberjack answered 12/6, 2023 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.