Saturday 13 May 2017

Express creates different session when auth header is changed

I am new to express and I am trying to create session when user logs in to my app.I am using passport for authentication. To login user I am creating basic strategy and on success of basic strategy I am creating a JWT token which I am storing at client side in cookie and I use JWT strategy for subsequent requests.

But I notice that express-session is creating one session when I am logging in which has Basic header and another session for subsequent calls which has JWT header.

Here is my code where I am saving session on login

signin = function(req, res, next) {
    passport.authenticate('basic', function(err, user, info) {
        if (err) { return next(err) }
        if (!user) {
            return res.status(401).json({ error: 'message' });
        }
        var token = jwt.encode({ user: user}, config.db.secret);
        res.cookie('token', token, { maxAge: 900000, httpOnly: true, path: '\/', Secure: true });
        res.status(200).json({ success: true, firstName: user.firstName });
        delete user.password;
        req.session.user = user;
        req.session.save();
    })(req, res, next);
};

But when I debug this code it shows one sessionID in req.sessionID and it show different sessionID in req.sessionID in the following code which as JWT authentication

listProducts = function(req, res) {
    debugger;
    //here req.session.user is undefined which I have saved at login. and sessionID is also different
    res.json({ demo: 'response' });
};

I am expecting it to be same sessionID throughout the life cycle till user logs out of my app. Why is this exactly happening? What is the solution to it?



via nikhil mehta

No comments:

Post a Comment