好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解决SpringBoot自定义拦截器和跨域配置冲突的问题

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

技术栈

vue-cli3,springboot 2.3.2.RELEASE

问题引出

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

原代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@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中实现跨域的配置。

新代码

?

1

2

3

4

5

6

7

8

9

@Configuration

public class WebConfig extends WebMvcConfigurationSupport {

     @Override

     protected void addInterceptors(InterceptorRegistry registry) {

         registry.addInterceptor( new AuthInterceptor())

                 .addPathPatterns( "/**" )

                 .excludePathPatterns( "/login/*" , "/register/*" );

     }

}

添加Filter

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@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处理的,可以很好的解决问题。  

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

?

1

2

3

4

5

6

7

@Configuration

public class WebConfig extends WebMvcConfigurerAdapter {

     @Override

     public void addCorsMappings(CorsRegistry registry) {

         registry.addMapping( "/**" );

     }

}

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

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

原文链接:https://blog.csdn.net/weixin_43876438/article/details/115602730

查看更多关于解决SpringBoot自定义拦截器和跨域配置冲突的问题的详细内容...

  阅读:20次