springboot解决ajax跨域访问,session丢失的问题 您所在的位置:网站首页 获取谷歌浏览器cookie springboot解决ajax跨域访问,session丢失的问题

springboot解决ajax跨域访问,session丢失的问题

2023-06-08 06:51| 来源: 网络整理| 查看: 265

亲测可用,若有疑问请私信

1、前端ajax

    $.ajax({         url: url,         type: 'post',         xhrFields: {withCredentials:true},    //前端适配:允许session跨域          data: data,         success: function(data) {         }     }); ajax加上这两句

    xhrFields: {withCredentials:true},    //前端适配:允许session跨域 2、后台Controller类加注解  SpringBoot 2.5.2

@CrossOrigin(originPatterns="*", allowCredentials="true", allowedHeaders = "*" ) // 前端跨域解决 DEFAULT_ALLOWED_HEADERS:允许跨域传输所有的header参数,将用于使用token放入header域 做session共享的跨域请求

3.在中转的业务方法增加

// springboot里面多加了samesite这个设置,需要降低其等级 去掉session会话共享会失败。 ResponseCookie cookie = ResponseCookie.from("JSESSIONID", httpServletRequest.getSession().getId() ) // key & value .httpOnly(true) // 禁止js读取 .secure(true) // 在http下也传输 .domain("localhost")// 域名 .path("/") // path .maxAge(3600) // 1个小时候过期 .sameSite("None") // 大多数情况也是不发送第三方 Cookie,但是导航到目标网址的 Get 请求除外 .build() ; httpServletResponse.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());

补充!本质原因如下:

     由于谷歌浏览器的SameSite安全机制的问题,浏览器在跨域的时候不允许request请求携带cookie,导致每次sessionId都是新的,这里有个出问题前提:跨域,刚好和调试时的环境情况一致。浏览器版本chrome 93.0.4577.82(谷歌游览器好像从80版本之后就加入了SameSite安全机制)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有