单点登录cookie跨域二三事之withCredentials
背景
随着前后端项目开发的流行现在前后端跨域非常常见。
典型案例
后端SpringBoot 端口8079
前端VueJs 端口8075
存在如下场景在8075需要通过jsonp访问8079数据
比如在192.168.1.153:9001画面上访问【8078后端已经使用SpringBoot配置cors】
SpringBoot配置如下WebMvcConfigurerAdapter
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
获取信息如下
$.get("http://192.168.1.153:8078/f6-insurance/insurance/insurance")
分析
通常报错如下
165218_zLdt_871390.png“细心”的我发现了如下请求
165234_OgDQ_871390.png302 是重定向
恩再细细看看 chrome报错是重定向的跨域失败
Redirect from 'http://192.168.1.153:8078/f6-insurance/insurance/insurance' to 'http://192.168.1.153:9001/?ReturnURL=http%253A%252F%252F192.168.1.153%253A8078%252Ff6-insurance%252Finsurance%252Finsurance' has been blocked by CORS policy
由于我们子系统都是用Cookie来做单点登录【cookie在主域名】因此当没接受到cookie信息时将会自动重定向到登录页面 而登录页是其他系统并未提供跨域请求 因此将会出现跨域失败【通常开发环境比较常见当production ready时由于vue代码也会放到同样的后端管理【或者nginx】】那我们的系统中由于通过cookie来做授权 那么cookie不存在或者服务端未接收到有效的认证cookie将会无法认证导致切换到登录再析Cookie&Session
但是当使用到端口时存在如下问题【虽然cookie跨域不存在端口限制】
- 在不同域做XHR请求【注意不是jsonp】时由于存在不同域【包括 协议 端口 域名】那么cookie【默认情况】将会无法传递
- 那么我们可以通过withCredentials来完成cookie的传递
The XMLHttpRequest.withCredentials property is a
Boolean
that indicates whether or not cross-siteAccess-Control
requests should be made using credentials such as cookies, authorization headers or TLS client certificates. SettingwithCredentials
has no effect on same-site requests.In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is
false
. XMLHttpRequest from a different domain cannot set cookie values for their own domain unlesswithCredentials
is set totrue
before making the request. The third-party cookies obtained by settingwithCredentials
to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.Note: This never affects same-site requests.
Note:
XmlHttpRequest
responses from a different domain cannot set cookie values for their own domain unlesswithCredentials
is set totrue
before making the request, regardless ofAccess-Control-
header values.
从上述可以看到cookie需要设置withCredentials来完成
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);