簡體   English   中英

Express-Session - 有沒有辦法在 ExpressJS 路由之外的會話中存儲數據?

[英]Express-Session - Is there a way to store data in a session outside of an ExpressJS route?

我有一個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)
        }
    });
}

非常感謝。

沒錯,全局變量在路由之外的范圍之外。 一個非常核心的方法是將會話數據存儲在磁盤文件中,並在需要時讀回。 但是有一些限制。 使用 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”。 看看四周。 祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM