之所以遇到这个问题是因为我在学websocket。。。。
本来session是个简单的东西,我在写jsp(前后端不分离)的时候用过,感觉so easy,但是今天我用h5+Springboot前后端分离,彻底炸开了锅,花了我不下5个小时,记录一下。
问题重现
看到别人的博客要改这个响应头,他们说设置这个Origin的值的时候不要用 * 这个图方便,因为前端需要带凭证过来,必须设置成具体的。这里我用的是liveserver开的项目所以端口是5500。
@Configuration
@WebFilter("/*")
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin","http://127.0.0.1:5500");
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");
filterChain.doFilter(servletRequest, servletResponse);
}
}
前端Ajax代码
她们说要设置这个withCredentials属性为true
$(".lg").click(function(){
$.ajax({
url: "http://localhost:8080/login",
data: JSON.stringify(
{
username:login.value
}
),
type: "POST",
contentType: "application/json;charset=utf-8",
xhrFields: {
withCredentials: true
},
success: function (data) {
console.log(data)
}
})
})
$(".getname").click(function(){
$.ajax({
url: "http://localhost:8080/getusername",
type: "GET",
contentType: "application/json;charset=utf-8",
xhrFields: {
withCredentials: true
},
success: function (data) {
console.log(data)
}
})
})
然后controller里加上这个注解
@RestController
@CrossOrigin(origins = "http://127.0.0.1:5500",allowCredentials = "true")
public class UserController
然后问题还是没解决,后端两次请求的session的值还是不一样。
后来在前端请求里逐步调试,最后发现了端倪,
浏览器这个请这里有个警告,。
跨域警告“此Set-Cookie标头未指定‘SameSite“届性,它默认为‘SameSite=Lax,必须为此SetCookie设置“SameSite=None“才能实现跨站点使用。
然后就用就找这个问题,在CSDN知乎等大佬的博客下终究是解决了。
只需要在springboot的配置文件里加两条配置就行了
#server.servlet.session.cookie.same-site=none
#server.servlet.session.cookie.secure=true
最后还是解决了。这个应该就是前辈为了浏览器的数据安全才给我们埋下了这些坑。