当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot2.x整合Shiro出现cors跨域问题(踩坑记录)

SpringBoot2.x整合Shiro出现cors跨域问题(踩坑记录)

2019年12月27日  | 移动技术网IT编程  | 我要评论

1. springboot如何跨域?

最简单的方法是:

定义一个配置corsconfig类即可(是不是简单且无耦合到令人发指)

@configuration
public class corsconfig {
 
    private corsconfiguration buildconfig() {
        corsconfiguration corsconfiguration = new corsconfiguration();
        corsconfiguration.addallowedorigin("*");
        corsconfiguration.addallowedheader("*");
        corsconfiguration.addallowedmethod("*");        
        corsconfiguration.setmaxage(3600l);         // 预检请求的有效期,单位为秒。
        corsconfiguration.setallowcredentials(true);// 是否支持安全证书(必需参数)
        return corsconfiguration;
    }
 
    @bean
    public corsfilter corsfilter() {
        urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
        source.registercorsconfiguration("/**", buildconfig());
        return new corsfilter(source);
    }
}

 

不要用webmvcconfigureradapter继承的方法了,因为已经过时了,springboot2.0已经不推荐此方法

此处有一个比较坑的地方就是:

corsconfiguration.setmaxage(3600l);         // 预检请求的有效期,单位为秒。
corsconfiguration.setallowcredentials(true);// 是否支持安全证书(必需参数)

这两句务必要加上,不然无论前端怎么做,也无论后台你对shiro的过滤器怎么重写,response请求返回状态都是302。

网络上大家的代码都是copy来copy去,往往没有这2句,所以这个坑真是眼泪汪汪。

 

2. 前端在发送请求是,是否需要加上跨域参数?(以下两句为跨域参数)

crossdomain: true,                       
xhrfields: {withcredentials: true},

答案是肯定的。

如果不加跨域参数,通过在shiroconfig中配置某些url不鉴权(匿名访问),倒也可以(但是不推荐,你不可能把所有的url都设置为匿名访问,那要鉴权做什么?)。

filterchaindefinitionmap.put("/login/**", "anon");   //类似于url路径中含有login的不鉴权

那么这两句的作用是什么?    -- 利用cookie维持session的会话跟踪。

 

good luck!

 

 

参考文章:https://blog.csdn.net/wangchsh2008/article/details/90324631

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网