Knife4j文档请求异常(更新)

文章目录

  • 1. 多模块注解不当引起
  • 2. SpringSecurity白名单问题

    1. 多模块注解不当引起

    在SpringBoot项目中,如果是分不同的模块开发。

    注解配置 @EnableSwagger2WebMvc不在启动类上,而是加到了其他模块的注解中,可能会导致这种情况发生。

    我的是common一个单独的模块,在common模块中配置了WebMvcConfig。

    然后在WebMvcConfig类上面加了注解@EnableSwagger2WebMvc.

    那么,解决方法也很简单,在启动类上也添加上注解@EnableSwagger2WebMvc即可。

    /**
     * @Author: KingWang
     * @Date: 2023/4/9
     * @Desc:
     **/
    @Slf4j
    @Configuration
    //@EnableSwagger2WebMvc 分模块下,这个注解不在启动类模块中,是无效的
    public class WebMvcConfig extends WebMvcConfigurationSupport { @Override
        protected void addResourceHandlers(ResourceHandlerRegistry registry) { //swagger文档需要添加下面2行
            registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        /**
         * 扩展mvc框架的消息转换器
         * @param converters
         */
        @Override
        protected void extendMessageConverters(List> converters) { log.info("扩展消息转换器...");
            //创建消息转换器对象
            MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
            //设置对象转换器,底层使用Jackson将java对象转为Json
            messageConverter.setObjectMapper(new JacksonObjectMapper());
            //将上面的消息转换器对象追加到mvc框架的转换器容器中
            converters.add(0, messageConverter);
        }
        @Bean
        public Docket adminApiConfig(){ List pars = new ArrayList<>();
            ParameterBuilder tokenPar = new ParameterBuilder();
            tokenPar.name("token")
                    .description("用户token")
                    .defaultValue("")
                    .modelRef(new ModelRef("string"))
                    .parameterType("header")
                    .required(false)
                    .build();
            pars.add(tokenPar.build());
            //添加head参数end
            Docket adminApi = new Docket(DocumentationType.SWAGGER_2)
                    .groupName("adminApi")
                    .apiInfo(adminApiInfo())
                    .select()
                    //只显示admin路径下的页面
                    .apis(RequestHandlerSelectors.basePackage("com.guigutool.system.controller"))
                    .paths(PathSelectors.regex("/admin/.*"))
                    .build()
                    .globalOperationParameters(pars);
            return adminApi;
        }
        private ApiInfo adminApiInfo(){ return new ApiInfoBuilder()
                    .title("后台管理系统-API文档")
                    .description("本文档描述了后台管理系统微服务接口定义")
                    .version("1.0")
                    .contact(new Contact("guigutool", "http://guigutool.com", "guigutool@qq.com"))
                    .build();
        }
    }
    

    启动类中加上该注解:

    @EnableSwagger2WebMvc
    @SpringBootApplication
    @MapperScan("com.guigutool.system.mapper")
    public class ServiceAuthApplication { public static void main(String[] args) { SpringApplication.run(ServiceAuthApplication.class,args);
        }
    }
    

    2. SpringSecurity白名单问题

    白名单设置的不全或者不一致导致的。

    在SpringSecurity中我们通常会增加配置类SecurityConfig如下设置:

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {private static final String[] http_ignore_path = {"/v2/**","/swagger-resources","/webjars/**","/favicon.ico","/doc.html","/log/*","/admin/system/index/login/"};
        @Override
        protected void configure(HttpSecurity http) throws Exception { http.csrf().disable()  //关闭csrf
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().cors().configurationSource(corsConfigurationSource())
            .and()
            .authorizeRequests()
            .antMatchers(http_ignore_path).permitAll()
            .anyRequest().authenticated();
            //添加用户认证过滤器
            http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
            //认证和权限
            http.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                    .authenticationEntryPoint(authenticationEntryPoint);
        }
    }
    

    这里要特别注意http_ignore_path 这个数组设置的白名单。

    Knife4j需要配置的白名单如下:

    private static final String[] http_ignore_path = {"/v2/**","/swagger-resources","/webjars/**","/favicon.ico","/doc.html","/log/*","/admin/system/index/login/"};
    

    除了最后两个"/log/*“,”/admin/system/index/login/"是日志和登录接口以外,其他的都需要放行。

    之前设置登录接口的时候一直也是卡住,即使添加了白名单也不放行,后来仔细检查终于发现登录的请求地址写错了。

    可以先在过滤器中打印出请求的URL信息如下:

     String requestURI = request.getRequestURI();
            log.info("请求URI:" + requestURI);
    

    这样可以看到请求的地址信息,然后将这里显示的URI信息,然后将这里的信息填写到白名单中。

    自己曾经在白名单中写登录请求地址时,多加了一个/ 导致一直登录失败。