简体   繁体   English

如何跨子域共享快速会话?

[英]How to share express sessions across subdomains?

I am using express-session and MongoDbStore to store session variables.我正在使用 express-session 和 MongoDbStore 来存储 session 个变量。 However after implementing subdomains using vhost, The session variables are not shared between the subdomains.然而,在使用 vhost 实现子域后,子域之间不共享 session 变量。 My session config is as follows我的session配置如下

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,
    }))

Sample vhost code:示例虚拟主机代码:

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

The session variables are stored in the MongoDB, but there are different documents for each subdomain. session变量存储在MongoDB,但是每个子域都有不同的文档。 How can i make those session variables universal for all my subdomains?我怎样才能使这些 session 变量对我的所有子域通用?

What i have tried till now: Keeping domain as '.example.com', not including the path parameter, not including the domain parameter, not including the httpOnly parameter, using resave as true But nothing seems to work Thank you in advance到目前为止,我一直在尝试:将域保持为“.example.com”,不包括路径参数,不包括域参数,不包括 httpOnly 参数,使用 resave as true 但似乎没有任何效果提前谢谢

I have found the solution while looking through other solutions in the forum, If someone comes across this try to use this express function:我在浏览论坛中的其他解决方案时找到了解决方案,如果有人遇到此问题,请尝试使用此快递 function:

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();
    });

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

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