提问者:小点点

在生产中调用destroy时,不会从Mongo存储中删除Express会话数据


我的应用程序的注销功能面临一个问题。

问题

调用req.session.destroy不会仅在生产中从Sessions MongoDB集合中删除会话数据。

请求命中服务器,logout方法运行,destroy函数没有返回错误,在会话上运行console.log显示它是空的,但在页面刷新上用户仍然登录,检查db.sessions.find()显示会话数据未被触及。

我认为子域的设置与此有关,正如预期的那样,本地工作。我只是不明白这是什么,因为应用程序的其他功能良好。

正在使用的密钥包

  • 快速-会话
  • 连接-mongo
  • CORS

该功能在本地运行良好(API和React应用程序都运行在localhost上,只是不同的端口)。

生产设置为

  • API.mydomain.com是带有Express API和Mongo DB的节点服务器。
  • app.mydomain.com是一个向API发送请求的React应用程序。

server.js-重要部分

    //use sessions for tracking logins
var sessionData = {
    name: 'secure_name', // for testing
    secret: 'secure_secret', // for testing
    resave: true,
    rolling: true,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection }),
    cookie: {
        "maxAge": (1000 * 60 * 60 * 7), // 7 days.
        secure: false,
        path: '/',
        domain: process.env.DOMAIN
    }
};

// Setup session with config and make the app use it.
var sessionMiddleware = session(sessionData);
app.use(sessionMiddleware);

...
// User - Logout.
app.get('/api/users/logout', user.logout);

user.logout方法

// Logout user.
exports.logout = (req, res, next) => {

    // Only if there is an active session.
    if (req.session) {

        // delete session object
        req.session.destroy(error => {

            req.session = null;
            if (error) return next(error);

            res.send({ logout: true })
        });
    }
}

反应注销方法请求

        // Logout - end this user session.
    @action logout() {

        // Destroy session.
        return axios.get(config.url + 'api/users/logout', {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json',
                },
            })

任何帮助都将不胜感激。


共1个答案

匿名用户

我找到了解决我问题的办法。在这里发帖,以防其他人遇到类似的问题。

发送到服务器的GET请求不包括任何凭据,因为默认情况下,该请求设置为false。

解决方案是在请求中将“with-credentials”显式设置为true,如下所示:

        // Logout - end this user session.
@action logout() {

    // Destroy session.
    return axios.get(config.url + 'api/users/logout', {
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json',
            },
            withCredentials: true
        })