简体   繁体   English

如何将Express会话用作身份验证处理程序

[英]How using express-session as authentication handler

I'm building a simple login app with express 4 and express-session. 我正在使用Express 4和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. 所有http请求都将通过会话中间件,访问者在访问的第一条路线上将获得一个空会话和一个密钥cookie。 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. 关于处理身份验证,我的第一个想法是检查请求的会话是否存在,如果为true =访问者已登录。但是,当访问者仅通过访问任何路线来获得其(空)会话时,这似乎并不合理。

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 ? 还是将属性添加到经过身份验证的会话中更好,例如: 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. 现在,我对Passwordjs等类似的中间件解决方案不感兴趣,因为我想从下至上学习它的工作原理。

I just did what you describe in your post, a login app with stored sessions (Redis in my case). 我只是按照您在帖子中描述的那样做,即一个带有存储会话的登录应用程序(在我的情况下为Redis)。

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 就我而言,我只是将会话内的属性设置为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 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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