简体   繁体   中英

How using express-session as authentication handler

I'm building a simple login app with express 4 and express-session.

If i do this:

app.use(session({
  store: new MongoStore({ db: 'sess' }),
  secret: 'Ninja Turtle',
  cookie: { path: '/', httpOnly: true, secure: false, maxAge: 3600000 } // 1 hour expiration
}));

All http request will flow trough the session middleware, and a visitor will get a empty session and a key cookie at the first route they visit. It does'nt matter if this route need authentication or not. It could be the login page.

My first thought regarding handling authentication, was to check if the requested sessions exist, if true = the visitor is logged in. But this doesn't seem reasonable when a visitor get his (empty) session just by visiting any route.

Should I somehow add the session middleware to only certain routes so a visitor dont get an empty session just by visiting any route?

Or is it better to add a property to authenticated sessions, like this: logged_in: true ?

Right now I'm not interested in middleware solutions like Passwordjs and similar, because I want to learn how this works from the bottom up.

I just did what you describe in your post, a login app with stored sessions (Redis in my case).

It's normal that every user has a session. So i won't consider to enable the session middleware only to certain routes because you may want, in the futur, to use user's session even for not logged users.

In my case i just set a property inside the session to true

if ( YourLogInCondition ) {
  req.session.logged = true;
  //rest of login action
}

It might not be the best approach but that's what i did.

Hope it helps.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM