Springboot 跨域 session 不一致的问题

网上已经有很多跨域解决方法了,这里说一个谷歌浏览器的例外: SameSite

https://developers.google.com/search/blog/2020/01/get-ready-for-new-samesitenone-secure

自 2020 年 2 月起执行 Chrome 强制措施
从 2 月份起,在 Chrome 80 中,Chrome 会将未声明 SameSite 值的 Cookie 视为 SameSite=Lax Cookie。只有采用 SameSite=None; Secure 设置的 Cookie 可用于外部访问,但前提是通过安全连接进行访问。适用于 SameSite=None 和 Secure 的 Chrome Platform Status 跟踪器会持续更新,列出最新的发布信息。

Mozilla 已经确认他们支持新的 Cookie 分类模型,并打算在 Firefox 中实现对跨网站 Cookie 的 SameSite=None; Secure 要求。Microsoft 最近宣布计划在 Microsoft Edge 80 中进行实验,开始实现该模型。

当你在 F12 浏览器中查看到 Set-Cookie 后面带有一个感叹号,那一般就是 SameSite 问题了

在 Springboot 中添加此配置即可

server:
port: 8080
servlet:
session:
cookie:
same-site: none
secure: true

文章转自:Springboot 跨域 session 不一致的问题_Java-答学网

作者:答学网,转载请注明原文链接:http://www.dxzl8.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 跨域Session Cookie失效问题的解决方法如下: 首先,跨域问题可以通过配置Spring Boot的CORS(跨源资源共享)来解决。在Spring Boot中,可以使用注解 `@CrossOrigin` 或在配置类中添加 `addCorsMappings` 方法来配置跨域的访问。 @CrossOrigin 注解可以应用在控制器类或方法上,指定允许跨域的来源、方法、头部、是否允许携带凭证(比如 Cookie)等参数。例如: ```java @CrossOrigin(origins = "http://localhost:8080", maxAge = 3600, allowCredentials = "true") @GetMapping("/example") public ResponseEntity<String> getExample() { // ... } ``` 另一种配置跨域方法是创建配置类,并继承 `WebMvcConfigurer` 接口,并重写其 `addCorsMappings` 方法。例如: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET", "POST") .allowCredentials(true) .maxAge(3600); } } ``` 其次,Session Cookie失效问题可以通过在跨域请求中添加凭证(Credentials)来解决。具体来说,可以将 `allowCredentials` 参数设置为 `true`,同时在请求头中添加 `withCredentials: true`。例如: ```javascript fetch('http://localhost:8080/api/example', { method: 'GET', credentials: 'include' // 或 'same-origin' }) ``` 这样配置后,Spring Boot就可以正常接收带有 Cookie 的跨域请求,并在服务端保持 Session 的有效性。 综上所述,通过配置跨域设置和同时在请求中添加凭证,可以解决Spring Boot跨域Session Cookie失效的问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值