springSecurity整合knief4j接口文档

  1. 添加如下依赖
        <!--knife4j(接口文档)-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
            <version>4.4.0</version>
        </dependency>
        <!--spring-boot版本不要太高-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
  1. 在yml配置文件中添加以下内容:主要是在spring底下mvc
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
  1. 在springsecurity中放行
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭跨域校验
                .csrf().disable()
                //关闭security默认session验证
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //授权
                .authorizeRequests()
                //放行想要放行的资源
                .antMatchers(
                       //下面是knief4j和swagger放行的内容,包含了好几个版本的knief4j,所以直接全部复制就行了
                        ,"/v3/api-docs"
                        , "/api/**"
                        ,"/doc.html"
                        , "/webjars/**"
                        , "/img.icons/**"
                        , "/swagger-resources/**"
                        , "/**"
                        , "/v2/api-docs"
                ).permitAll() // 允许匿名访问
                // 任何请求都需要认证
                .anyRequest().authenticated();

    }
  1. 在yml文件中配置你的controller的位置
# 接口文档配置
knife4j:
  enable: true
  openapi:
    title: "接口文档"
    version: 1.0
    group:
      default:
        api-rule: package
        api-rule-resources:
          - com.test.controller # 你的接口的位置
  1. 访问路径即可:http://localhost:{port}/doc.html port是你的端口号 例如下方
http://localhost:8080/doc.html#/home
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐