Saturday 11 March 2017

HMAC for request body does match in Node.js

I am building some RESTful APIs using node.js. I am new to node.js. I literally 2 days ago. Here is what I am try to do.

Sending the following request using postman.

POST /register HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Authorization: 415952c44ac7de13f01cdf46bac5e590f29ff12211054e16f71098ca8909652b
Cache-Control: no-cache
Postman-Token: 26087979-05c0-1d75-8822-41809272ef46

{
    "email":"a@abc.com", 
    "name": "abc xyz"
}

The value for Authorization header is computed HMACSHA256 for the request body. For testing, I used http://www.freeformatter.com/hmac-generator.html to compute HMACSHA256 and I made sure that I am using the same secret key to compute hmac.

In Node.js I am using the same request body to compute the HMACSHA256 using the following code

app.use(bodyParser.json({
    verify: function (req, res, buf, encoding) {
        console.log('json encoding: ', encoding);
        var hmac = crypto.createHmac('sha256', 'a secret');
        hmac.update(buf.toString());
        req.hasha = hmac.digest('hex');
        console.log("hmac: ", req.hasha);

        // get rawBody
        req.rawBody = buf.toString();
        console.log(req.rawBody);

    }
}));

The problem is, that gives me wrong HMACSHA256 value. It feels like something is being modified before I process the buffer. I am not sure what am I doing wrong or if there is a better way of doing it.



via Avigit

No comments:

Post a Comment