关于前后端分离SpringSecurity设置Cookie的问题
今天刚入手SpringSecurity,很多不是太懂,在github找到个dome
github地址:https://github.com/ChinaSilence/spring-security-demos
然后发现SpringSecurity登录成功之后访问需要登录的接口依然是返回未登录,看了demo中的文档,登录成功之后响应头会携带一个cookie绑定到本地,然后请求需要登录的接口的时候需要携带这个cookie。
在登录接口响应头中有set-cookie 但是本地cookie还是空的,傻傻的以为ajax请求的时候需要自定义请求头加上cookie,发现请求头不允许携带cookie,cookie是自动携带的。这就找到问题所在了,因为是前后端分离项目,cookie跨域了,所以导致cookie无法保存,也无法携带
解决办法:后端允许cookie跨域
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse resp = (HttpServletResponse) response;
HttpServletRequest rep = (HttpServletRequest) request;
resp.addHeader("Access-Control-Allow-Origin", rep.getHeader("Origin"));
//允许跨域请求中携带cookie
resp.addHeader("Access-Control-Allow-Credentials", "true");
// 如果存在自定义的header参数,需要在此处添加,逗号分隔
resp.addHeader("Access-Control-Allow-Headers", "authorization,Origin, No-Cache, X-Requested-With, "
+ "If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, " + "Content-Type, X-E4M-With");
resp.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
chain.doFilter(request, response);
}
前端ajax允许cookie跨域:
ajax请求添加以下参数:
crossDomain: true,
xhrFields: {
withCredentials: true
},
整体ajax为:
$.ajax({
url : patl,
type: "POST",
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(result) {
alert("success");
}
});
`
也可以在ajax拦截器里面配置,另外解惑的文章附上
https://my.oschina.net/qinghang/blog/1608792