让两个网站的Session共用 🔗
当我们开发网站的时候,可能需要让不同子域名的网站之间的session能够共用,以达到后端授权通用的效果。但是即使在设置了session作用域为两个子域名的父域名后,session依旧无法通用。因为在使用nginx进行了跨域请求时,请求虽然没有报错跨域,但是请求的header中不带cookie字段。原因是浏览器的同源策略导致,需要进行一下配置。
前端请求设置 🔗
在前端请求时需要设置xhrFields,将withCredentials设置为true,示例代码如下:
javascript
$.ajax({
url: 'http://example.com',
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
}
});
后端设置 🔗
允许携带 Cookie 🔗
在后端需要设置允许携带 Cookie,设置方法为:
nginx
add_header Access-Control-Allow-Credentials "true";
如果不开启的话,会报错:
csharp
Access to XMLHttpRequest at 'http://example.com' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is 'false' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
允许特定的请求头 🔗
在设置了允许携带 Cookie 后,还需要设置允许特定的请求头,可以使用Access-Control-Allow-Headers,示例代码如下:
nginx
add_header Access-Control-Allow-Headers '*,provider';
最后,如果在origin设置通配符,可能会因为安全原因报错,错误信息如下:
csharp
Access to XMLHttpRequest at 'http://example.com' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
需要将Access-Control-Allow-Origin设置为具体的域名,不能使用通配符。
nginx
add_header Access-Control-Allow-Origin "http://xxx";
以上是让两个网站的Session共用的解决方案,希望可以帮助到有需要的开发者。