现在很多都是前后端分离的项目,那么就会产生跨域问题
现在新版本chrome浏览器cookie新增一个属性SameSite。
SameSite可以设置有三个值:
Strict
Lax
None
None的话,就不做是否同站的检查和限制
@Configuration
@WebFilter(filterName = "corsFilter")
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
String origin = request.getHeader("Origin");
String sessionId = "JSESSIONID="+request.getSession().getId();
response.setHeader("Access-Control-Allow-Origin",origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,authorization");
response.setHeader("Set-Cookie",sessionId + ";path=/;Secure;SameSite=None");
filterChain.doFilter(servletRequest,response);
}
}
response.setHeader("Set-Cookie",sessionId + ";path=/;Secure;SameSite=None");
主要是加入这一行,把SameSite设置为None,且Secure必须放在前面
当SameStie设置为None后请求必须是https。所以要配置一下https
在springboot的yml文件下配置下https,证书可以用自行用免费的
前端ajax需加上这2个属性
xhrFields: {
withCredentials: true
},
crossDomain: true
这样就可以解决研发或者测试环境跨域cookie传不到后台的问题