goloving

  跨域种cookie的问题就是,比如a.123.com跨域访问b.123.com/request,b.123.com服务器使用nginx允许跨域,Access-Control-Allow-Origin:*

  如果a、b服务不在同一个服务器,前台页面请求报错信息为:

    Access to XMLHttpRequest at \'http://b.123.com\' 
    from origin \'http://a.123.com\' has been blocked by CORS policy: 
    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.

  对应ajax请求为:

$.ajax({
  url : \'http://b.123.com/request\',
  data : data,
  dataType: \'json\',
  type : \'POST\',
  xhrFields: {
    withCredentials: true
  },
  crossDomain: true,
  ...

  此时,应取消nginx设置的跨域*,改成代码端设置。且代码服务器端通过在响应 header 中设置

response.setHeader("Access-Control-Allow-Credentials", "true");

  来运行客户端携带证书式访问。通过对 Credentials 参数的设置,就可以保持跨域 Ajax 时的 Cookie。

  服务器端 Access-Control-Allow-Credentials = true时,Access-Control-Allow-Origin 的值不能为 \'*\' ,应设置为发起请求的地址。

// a.com发来的请求
response.setHeader("Access-Control-Allow-Origin", a.123.com);

  b服务器在设置cookie时,需设置

cookie.setPath("/");
cookie.setDomain("123.com");

  否则设置的cookie无法生效。

 

分类:

技术点:

相关文章: