【问题标题】:How to share express sessions across subdomains?如何跨子域共享快速会话?
【发布时间】:2021-01-25 19:38:52
【问题描述】:

我正在使用 express-session 和 MongoDbStore 来存储会话变量。 但是,在使用 vhost 实现子域之后,会话变量不会在子域之间共享。 我的会话配置如下

app.use(session({
        secret: process.env.EXPRESS_SECRET,
        cookie: {
            path     : '/',
            domain   : 'example.com',
            httpOnly : false,
            maxAge   : 1000*60*60*24*7
        },
        store: store,
        resave: false,
    }))

示例虚拟主机代码:

app.use(vhost('login.example.com' , loginApp))
app.use(vhost('some.example.com' , someApp))

会话变量存储在 MongoDB 中,但每个子域都有不同的文档。 如何使这些会话变量对我的所有子域通用?

到目前为止我已经尝试过: 保持域为'.example.com',不包括路径参数,不包括域参数,不包括httpOnly参数,使用resave为true 但似乎没有任何效果 提前谢谢你

【问题讨论】:

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


【解决方案1】:

我在浏览论坛中的其他解决方案时找到了解决方案, 如果有人遇到这种情况,请尝试使用此快速功能:

app.use(function(req, res, next) {

        // Access-Control-Allow-Origin only accepts a string, so to provide multiple allowed origins for requests,
        // check incoming request origin against accepted list and set Access-Control-Allow-Origin to that value if it's found.
        // Setting this value to '*' will allow requests from any domain, which is insecure.        
        var allowedOrigins = ['https://subdomain1.domain.com', 'https://subdomain2.domain.com' , 'https://subdomain3.domain.com'];
        var acceptedOrigin = allowedOrigins.indexOf(req.headers.origin) >= 0 ? req.headers.origin : allowedOrigins[0];
        res.header("Access-Control-Allow-Origin", acceptedOrigin);
        next();
    });

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2010-09-21
    • 1970-01-01
    相关资源
    最近更新 更多