单点登录cookie跨域二三事之withCredentials


声明:本文转载自https://my.oschina.net/qixiaobo025/blog/1581685,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

背景

随着前后端项目开发的流行现在前后端跨域非常常见。

典型案例

后端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")

分析

通常报错如下

“细心”的我发现了如下请求

302 是重定向

恩再细细看看 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跨域不存在端口限制】

  1. 在不同域做XHR请求【注意不是jsonp】时由于存在不同域【包括 协议 端口 域名】那么cookie【默认情况】将会无法传递
  2. 那么我们可以通过withCredentials来完成cookie的传递

The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials 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 unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials 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 unless withCredentials is set to true before making the request, regardless of Access-Control- header values. 

 从上述可以看到cookie需要设置withCredentials来完成

var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/', true); xhr.withCredentials = true; xhr.send(null);

 

本文发表于2017年11月29日 18:33
(c)注:本文转载自https://my.oschina.net/qixiaobo025/blog/1581685,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 12100 讨论 123 喜欢 3

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1