目录
  • springboot自定义拦截器和跨域配置冲突
  • springboot 拦截器和addcorsmappings冲突

    springboot自定义拦截器和跨域配置冲突

    技术栈

    vue-cli3,springboot 2.3.2.release

    问题引出

    在做毕业设计过程中用到了自定义拦截器验证登录。同时在springboot配置类中设置了跨域问题,出现跨域失败的情况。

    原代码

    @configuration
    public class webconfig extends webmvcconfigurationsupport {
        @override
        protected void addcorsmappings(corsregistry registry) {
            registry.addmapping("/**")
                    .allowedorigins("*")
                    .allowedmethods("get", "head", "post","put", "delete", "options")
                    .allowedheaders("*")
                    .maxage(3600);
            super.addcorsmappings(registry);
        }
        @override
        protected void addinterceptors(interceptorregistry registry) {
            registry.addinterceptor(new authinterceptor())
                    .addpathpatterns("/**")
                    .excludepathpatterns("/login/*","/register/*");
        }
    }
    

    经过了解和排查发现,当有请求发送到后台时,先被自定义拦截器拦截,如果拦截器验证没有问题,才会开始执行跨域配置。因此解决办法是让跨域配置在自定义拦截器之前执行。而filter的执行顺序大于自定义拦截器,因此可以在filter中实现跨域的配置。

    新代码

    @configuration
    public class webconfig extends webmvcconfigurationsupport {
        @override
        protected void addinterceptors(interceptorregistry registry) {
            registry.addinterceptor(new authinterceptor())
                    .addpathpatterns("/**")
                    .excludepathpatterns("/login/*","/register/*");
        }
    }
    

    添加filter

    @configuration
    public class mycorsfilter{
        private corsconfiguration corsconfig(){
            corsconfiguration corsconfiguration = new corsconfiguration();
            corsconfiguration.addallowedheader("*");
            corsconfiguration.addallowedmethod("*");
            corsconfiguration.addallowedorigin("*");
            corsconfiguration.setmaxage(3600l);
            corsconfiguration.setallowcredentials(true);
            return corsconfiguration;
        }
        @bean
        public corsfilter corsfilter(){
            urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
            source.registercorsconfiguration("/**",corsconfig());
            return new corsfilter(source);
        }
    }

    springboot 拦截器和addcorsmappings冲突

    项目中最开始跨域问题是通过自定义过滤器corsfilter对request处理的,可以很好的解决问题。  

    最近,新项目中准备通过如下代码解决跨域问题,结果发现登录超时的错误会出现跨域问题,其他问题都不会。

    @configuration
    public class webconfig extends webmvcconfigureradapter {
        @override
        public void addcorsmappings(corsregistry registry) {
            registry.addmapping("/**");
        }
    }

    因为登录超时的检查是在拦截器中,所以推测是可能是拦截器的执行在addcorsmappings生效之前。将corsfilter代码拿到项目中后,果然没有这个问题了。所以这个bu基本上可以认定是是拦截器和addcorsmappings生效顺序的问题。

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。