【问题标题】:Express-Session - Is there a way to store data in a session outside of an ExpressJS route?Express-Session - 有没有办法在 ExpressJS 路由之外的会话中存储数据?
【发布时间】:2020-04-04 19:48:32
【问题描述】:

我有一个 passportJS 回调,当新用户尝试进行身份验证时,我不希望将新用户数据存储在数据库中,而是在快速会话中以供以后访问,这可能吗?

目前我的代码是:

function facebookAuthenticate(accessToken, refreshToken, profile, done) {
    User.findOne({ facebookID: profile._json.id }, (err, foundUser) => {
        if (foundUser) {
            done(err, foundUser);
        } else {
            global.authenticationID = { facebookID: profile._json.id };
            done(err, null)
        }
    });
}

但由于全局变量不是用户特定的,它一次只能用于一种身份验证。

理想情况下,我想要一些可以按照这些思路工作的东西,但我当然无法访问路由之外的 req 变量:

function facebookAuthenticate(accessToken, refreshToken, profile, done) {
    User.findOne({ facebookID: profile._json.id }, (err, foundUser) => {
        if (foundUser) {
            done(err, foundUser);
        } else {
            req.session.authenticationID = { facebookID: profile._json.id };
            done(err, null)
        }
    });
}

非常感谢。

【问题讨论】:

    标签: node.js express session passport.js express-session


    【解决方案1】:

    没错,全局变量超出了路由的范围。一个非常核心的方法是将会话数据存储在磁盘上的文件中,并在需要时将其读回。但是有一些限制。使用 jwt auth,您可以将数据存储在浏览器会话和 cookie 中。

    一个简单的想法是先在express上创建一个会话,

    var sessions    = require("client-sessions");
    app.use(sessions({
          cookieName: 'expSessions', // cookie name dictates the key name added to the request object
          secret: 'somesuperSecret', // should be a large unguessable string
          duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
          activeDuration: 1000 * 60 * 5, // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
            cookie: {
                path: '/', // cookie will only be sent to requests under '/api'
                maxAge: 60000, // duration of the cookie in milliseconds, defaults to duration above
                ephemeral: false, // when true, cookie expires when the browser closes
                httpOnly: true, // when true, cookie is not accessible from javascript
                secure: true // when true, cookie will only be sent over SSL. use key 'secureProxy' instead if you handle SSL not in your node process
            }
        }));
    

    另外,有许多 npm 包可用于会话处理,例如“express-session”。周围看看。祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 2014-02-27
      • 1970-01-01
      • 2011-06-10
      • 2021-10-29
      相关资源
      最近更新 更多