Session creation only after successful authentication in express

I have a requirement to create a session only after successful authentication.

I was able to create a redisStore based session using express middleware, but it creates a session when the first request comes to the server.

But how can I create a session only after successful authentication. I googled a bit and found req.session.regenerate()

(but I found the problem as mentioned below in this thread: Recover Session IDs with Nodejs Connect )

But in the case of regeneration, it creates a new one, assuming that the old one has already been created, and is created with the same parameter.

So there is another way to create a new session ID only after successful authentication.?

+3


source to share


2 answers


You can combine the idea of ​​a session with the idea of ​​an authenticated session.

Usually there is a session for all users - even anonymous, not yet registered users. The difference between this and a verified session is precisely that locally on your web server, you indicate that a specific user has been authenticated.

For example, once you authenticate someone, you can set:



req.session.isAuthenticated = true;

      

Then when rendering the pages, your controllers can do something like

function(req, res, next) {
  if (!req.session.isAuthenticated) return res.redirect('/login');
  res.render('appPage');
}

      

+3


source


This may not be the exact answer you are looking for, but I will answer the title for future readers:

From experimenting with my application, I noticed that express-session only sets the session cookie if you manipulate the session object .

For example, consider the code below:

app.post('/login', function (req, res) {
  var authenticated = false;
  if (req.session.authenticated) {
    // session cookie is already set
    authenticated = true;
  } else if (/*validate the user here*/) {
    console.log(' authenticating');
    authenticated = true;
    // if below line executes, the response will have Set-Cookie header
    req.session.authenticated = authenticated;
  }
  res.json({
    status: authenticated
    //if --^ false, no session cookie will be set since we didn't manipulate session object
  });
 });

      



Even though the request creates a session object in memory for us to use, the header Set-Cookie

only seems to be sent if we manipulate (or fake?) The created session object.

If we didn’t send the header Set-Cookie

along with the response and session id, it is stored in a cookie on the client side, I would not treat it as an established session and not worry about it.

Hope it helps.

Side note. This is the case of cross-domain ajax request, may be different for normal HTTP request, maybe someone can confirm this.

+2


source







All Articles