Knife4j文档请求异常(更新)

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<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器...");
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器,底层使用Jackson将java对象转为Json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器对象追加到mvc框架的转换器容器中
        converters.add(0, messageConverter);
    }


    @Bean
    public Docket adminApiConfig(){
        List<Parameter> 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信息,然后将这里的信息填写到白名单中。
自己曾经在白名单中写登录请求地址时,多加了一个/ 导致一直登录失败。
在这里插入图片描述

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

硅谷工具人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值