I am setting a cookie using Connect’s cookieSession(). This seems to encrypt the cookie’s secret value, returning something like ‘s:j:{}.8gxCu7lVJHVs1gYRPFDAodK3+qPihh9G3BcXIIoQBhM’
How do I decrypt the cookie’s value?
Example code:
app.use(express.bodyParser());
app.use(express.cookieParser());
app.get('/setcookie', function(req, res, next){
res.app.use(express.cookieSession({ key: "test", secret: "test" }));
console.log(req.cookies.test);
res.end();
});
app.get('/', function(req, res, next){
console.log(req.cookies.test);
res.end();
});
Hmmm… you seem to be a bit confused about the use of cookie sessions.
Your
/setcookiepath doesn’t set any cookie/session values. To use a cookie session, you need to set some values onreq.session, for examplereq.session.message = "Hi there!"These values are now stored in the cookie.You can’t
res.app.use()in just one callback, the request session won’t work anywhere else this way. To read those cookies in another request, put theapp.use(express.cookieSession({ key: "test", secret: "test" }));at the application level.Edit: Actually I’ve thought about your res.app.use() call and it could break your app / cause memory to leak by adding more and more middleware layers (cookieSession) to your app, each time someone requests
/setcookie. If you want to only add the cookieSession middleware in specific requests, you need to do the following:Solution
This is the actual fixed source:
Now to inspect those values, in
app.get('/',...)try this:Debugging
And to answer the question of how to manually decode what’s stored in a cookie, look in
connect/lib/middleware/cookieSession.js:It takes
req.cookies[key](basically what you’ve been doing already (req.cookies.test)), pops it intoutils.parseSignedCookieand pops that intoutils.parseJSONCookie.I put your raw cookie string into the utils.js file at the end:
and ran that. Guess what I got:
Why? Because you never set anything on the
req.sessionobject. 🙂