javascript - 将服务器移动到 CORS 位置时 Passport/Express session 身份验证中断

标签 javascript angularjs cookies express cors

我正在使用 angular.js 和 ionic 构建一个应用程序。我将所有前端应用程序的内容移动到一个包中,并将服务器逻辑移动到 digital ocean 上它自己的液滴中。现在前端要做CORS。在初始身份验证中,除了 Express 响应中的 cookies 对象为空之外,一切似乎都运行良好。

当它起作用时,没有 CORS。我得到了这个

 cookies: { 'connect.sid': 's:ZrKJ7BxH2yeAiFG5uTC2FlhpfCa9S17K.oA5bCUQjZbdJBS8ohzngSiOEFzJWCyKxLDlBdEUqhzk' },

现在,当服务器在 Droplet 上运行并启用 CORS 时,我从响应中得到此信息

  cookies: {},

唯一不同的是请求来自 CORS。两者均未设置“env”,因此它们都默认为开发。

我设置的 CORS 是这样的:

var allowCrossDomain = function(req, res, next) {
    console.log("In allow cross domain function", req.headers)
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Credentials', true);
    next();
}

在 Chrome 开发人员工具中,我从未在资源/cookie 选项卡中看到 cookie,但在执行 CORS 之前我看到过...现在肯定是响应被发送回不同的域,对吗?我想不出还有什么会导致护照/ express 无法像“单域”设置之前那样工作。

编辑:我也会发布快速 session 代码,尽管这在移动服务器之前是有效的。

app.use(session({
    secret: app.getValue('env').SESSION_SECRET,
    store: new MongoStore({mongooseConnection: mongoose.connection}),
    cookie: { maxAge: 60000, secure: false },
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function (user, done) {
    console.log('Passport serializing user =>', user)
    done(null, user._id);
});

passport.deserializeUser(function (id, done) {
    console.log('Received this id => ', id)
    UserModel.findById(id, done);
});

最佳答案

您不能为包含 cookie 的请求设置来源通配符。

CORS with credentials

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *.

此外,如链接所述,您需要将 withCredentials: true 设置为 AJAX 请求。

关于javascript - 将服务器移动到 CORS 位置时 Passport/Express session 身份验证中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424699/

相关文章:

c# - 在 .net 中重置 IIS 后经过身份验证的用户

javascript - 将点击转换为 onmouseover javascript

python - 在 twisted.web.client 中使用 cookie

flutter - Google Analytics、Flutter、cookies 和通用数据保护条例 (GDPR)

javascript - angular.js 没有将 css 应用于附加的 html 元素?

javascript - 将参数从 twig 传递到 Angular

javascript - 如何从函数返回不同的 promise ?

javascript - 将 ajax 调用中的 html 附加到影子 DOM

javascript - 调试 javascript 函数

javascript - 循环最多 x 个数字,或更少