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


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

  • kisso
  • crossdomain
  • withCredentials
  • cookie
  • 跨域 categories: 工作日志 date: 2017-11-30 01:54:19

背景

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

典型案例

后端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);
复制代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值