'How to decode express-session cookies?

I isolated the problem, as far as I could, but still cannot solve it.

I created an empty server with loopback, added express-session and body-parser middlewares

 "session": {
    "express-session": {
      "params": {
        "name": "id",
        "secret": "potato with eyes",
        "httpOnly": "false"
      }
    }
  },
  "auth": {},
  "parse": {
    "body-parser": {},
    "body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}
  }

Then, I added a pair of methods to root.js.. The first sets session.id to a variable. The second logs it on next request:

module.exports = function (app)
{
    var cookieParser = require("cookie-parser")
    var router = app.loopback.Router()
    router.post("/login", function (req, res)
    {
        req.session.id = req.body.id
        console.log("Set id to " + req.body.id)
        res.end()
    })
    router.post("/addLead", function (req, res)
    {
        console.log("session", req.session)
        console.log("got id: ", req.session.id)
        console.log("decrypting single id:", cookieParser.signedCookie(req.session.id, "potato with eyes"))
        console.log("cookie! ", req.cookie)
        console.log("cookie parsed:", cookieParser.JSONCookie(req.cookie, "potato with eyes"))
        console.log("cookie parsed:", cookieParser.signedCookie(req.cookie, "potato with eyes"))
        res.status(403).send("You must login first")
    })
    app.use(router)
}

Decryption of cookies fails. Decryption of id does not change it.

Web server listening at: http://localhost:3000
Browse your REST API at http://localhost:3000/explorer
Set id to 15
session Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }
got id:  XifrUZXLhKcDHYqQwxESQlLQQ6N1j49d
decrypting single id: XifrUZXLhKcDHYqQwxESQlLQQ6N1j49d
cookie!  undefined
cookie parsed: undefined
cookie parsed: undefined

Here is the html I used for testing:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"
            integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="
            crossorigin="anonymous"></script>

    <script>
        function log(data)
        {
            console.log(JSON.stringify(data))
        }
        $.post("http://localhost:3000/login", { name: "John Smit", id: 15 }, function (data)
        {
            log(data)
            $.post("http://localhost:3000/addLead", {
                name: "Anton Berezin", phone: "337225", model: "1234",
                mark: "Toyota", yearFrom: "2014", yearTo: "2017"
            }, function (data)
            {
                log(data)
                alert(JSON.stringify(data))
            })
            .fail(function (error)
            {
                log(error)
            })

        })
        .fail(function(error)
        {
            alert(JSON.stringify(error))
        })
    </script>
</head>
<body>

</body>
</html>

And the archive with a project: http://www.filedropper.com/cookietest

I'll appreciate any help


Edit: tested with req.cookie instead of req.session.cookie. Didn't change output.



Solution 1:[1]

You don't need to use cookie-parser with express-session anymore.

Since you registered express-session, I would modify your code in this way

module.exports = function (app)
{
    var router = app.loopback.Router()

    // serialize the session
    router.post("/login", function (req, res)
    {
        req.session = {
           userId: 123,
           accessToken: 'eadeadaew'
           // or whatever data you want to store in the session
        };
        console.log("Set session");
        res.end();
    });

    // deserialize the session
    router.post("/addLead", function (req, res)
    {
        if(req.session) {
            console.log("session", req.session);
            console.log("user id: ", req.session.userId);
            console.log("token ", req.session.accessToken);
            res.end();
        } else {
            res.status(403).send("You must login first");
        }
    })
    app.use(router);
}

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