项目使用了SpringSecurity框架,登录成功后会设置cookie,cookie信息如图:
跨域登录成功后(自动设置了cookie),后续的其他请求没有自动携带cookie。
解决
cookie的属性介绍:https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
- 当设置
SameSite=none
时,跨域请求才会携带 cookie - 当设置
SameSite=none
时,必须设置secure=true
,浏览器才会存储cookie
所以,需要在后端生成cookie时设置 SameSite=none
和 secure=true
!
具体操作:
- 设置
SameSite=none
import org.apache.tomcat.util.http.Rfc6265CookieProcessor;
import org.apache.tomcat.util.http.SameSiteCookies;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TomcatConfig {
@Bean
public TomcatContextCustomizer sameSiteCookiesConfig() {
return context -> {
final Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor();
// 设置Cookie的SameSite:设置为NONE,支持跨站传cookie。!!!不安全
cookieProcessor.setSameSiteCookies(SameSiteCookies.NONE.getValue());
context.setCookieProcessor(cookieProcessor);
};
}
}
- 设置
secure=true
,application.yml
server:
servlet:
session:
cookie:
secure: true
reference:
Springboot应用中设置Cookie的SameSite属性