Spring Boot + Spring Security + JWT 集成Swagger文档问题

 现在的新项目框架都选择用Spring Boot,之前的旧项目,开发完对外的接口还需要自己写接口文档,在新项目中集成Swagger文档,这样就省去了我们写文档的时间,前端调用还可以利用它进行接口测试。
 简单的一个Spring Boot框架,很简单地几步就可以将Swagger文档配置集成好,如下:
 一 . 添加Swagger依赖 

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

 二 . 添加Swagger配置类 

@Configuration
@EnableSwagger2
public class Swagger {
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.uqiauto.trace.business"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("区块链追溯系统 后台接口文档")
                .description("")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}

 通过@Configuration注解,表明它是一个配置类,@EnableSwagger2开启swagger2。apiINfo()配置一些基本的信息。apis()指定扫描的包会生成文档。
  
 三 . 使用文档的相关注解
 
 swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

 @Api:修饰整个类,描述Controller的作用
 @ApiOperation:描述一个类的一个方法,或者说一个接口
 @ApiParam:单个参数描述
 @ApiModel:用对象来接收参数
 @ApiProperty:用对象接收参数时,描述对象的一个字段
 @ApiResponse:HTTP响应其中1个描述
 @ApiResponses:HTTP响应整体描述
 @ApiIgnore:使用该注解忽略这个API
 @ApiError :发生错误返回的信息
 @ApiParamImplicitL:一个请求参数
 @ApiParamsImplicit 多个请求参数
 
  Spring Security集成Swagger上面的几步是不能成功的,会遇到不少问题。所以还需要多配置几步。
  问题一: 访问页面404,需要在Swagger配置类中,增加swagger相关资源
 

@Configuration
@EnableSwagger2
@EnableWebMvc
public class Swagger extends WebMvcConfigurerAdapter{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.uqiauto.trace.business"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("区块链追溯系统 后台接口文档")
                .description("")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}

  问题二: 访问页面403,访问被拒绝,这和Spring Security就有关系,所以我们需要在Security相关配置类中添加Swagger相关请求允许访问

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
     httpSecurity.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
             .and().authorizeRequests()
             // 所有/trace/user/ 的所有请求 都放行
             .antMatchers("/trace/users/**").permitAll()
             // swagger start
             .antMatchers("/swagger-ui.html").permitAll()
             .antMatchers("/swagger-resources/**").permitAll()
             .antMatchers("/images/**").permitAll()
             .antMatchers("/webjars/**").permitAll()
             .antMatchers("/v2/api-docs").permitAll()
             .antMatchers("/configuration/ui").permitAll()
             .antMatchers("/configuration/security").permitAll()
             // swagger end
             // 所有请求都需要认证
             .anyRequest().authenticated();
     httpSecurity.headers().cacheControl();
     httpSecurity.csrf().disable();
     httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
 }

  问题三: 访问页面,弹出提示框:Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually
  遇到这个问题,那么很有可能是它要访问的url不在上面代码的 antMatchers 里,按ant规则添加就是了。
 使用示例

/**
 * 根据id查询用户
 *
 * @param id
 * @return
 */
@GetMapping("/users/{id}")
@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
public ReturnMsg findById(@PathVariable Long id) {
    ReturnMsg msg = ReturnMsg.getSuccessMsg();
    msg.putData("result",this.userService.findById(id));
    return msg;
}

猜你喜欢

转载自blog.csdn.net/u013034223/article/details/80462110