'How to sign a cookie manually using cookieParser?

For the sake of testing, I need to provide a signed cookie with HTTP request. So that, my Express app server can consider it as a signed cookie and put it into req.signedCookies object.

However I cannot find a appropriate method in docs.

I'd like to do the following:

let signed = cookieParser.signYourCookie({ cookieName: 'cookieValue' }, secretString);
// => cookieName=cookieValue.9PuJzypXeGq3tc2fFvlukjgNZ518jk

That is an operation opposite to cookieParser.signedCookie(str, secret) method. ExpressJS does it automatically under the hood, but there is a need to sign a cookie manually sometimes and the method seems missing.

To explain why I need this. I use Chai-http and need to set a cookie with the request. And I need it to be a signed cookie, so my server could find it it req.signedCookies object:

chai.request('http://foo.com')
    .get('/url/path')
    .set('my-signed-cookie', 'value-of-my-signed-cookie')


Solution 1:[1]

The plugin doesn't have public methods for that. Which is odd, actually. So I pulled the piece from plugin's code.

Do in your app:

var crypto = require('crypto');

function sign(val, secret){
  return val + '.' + crypto
    .createHmac('sha256', secret)
    .update(val)
    .digest('base64')
    .replace(/=+$/, '');
};

// Pay attention to `s:` prefix. With that, plugin considers it as a signed cookie, apparently 
.set('cookie', 'my-signed-cookie=s:' + sign('value-of-my-signed-cookie', 'my-cookie-secret'))

// Is equivalent to
.set('cookie', 'my-signed-cookie=s:value-of-my-signed-cookie.Dq+0CW44ZLfvzVWqEZEcK51X6auKaz771jFy4Zs4lWk')

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 Nate