关于SpringSecurity设置Cookie的问题

关于前后端分离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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值