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;
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot是一个用于创建独立的、基于生产级别的Spring应用程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更专注于业务逻辑的实现。 MyBatis Plus是MyBatis的增强工具,它提供了一系列的便利功能和增强特性,使得使用MyBatis更加简单和高效。它包括了代码生成器、分页插件、逻辑删除、乐观锁等功能,可以大大提高开发效率。 Redis是一个开源的内存数据库,它支持多种数据结构,如字符串、哈希、列表、集合、有序集合等。Redis具有高性能、高可用性和可扩展性的特点,常用于缓存、消息队列、分布式锁等场景。 Driver是指数据库驱动程序,它是用于连接数据库和执行SQL语句的软件组件。在Spring Boot中,我们可以通过配置数据源和引入相应的数据库驱动程序来实现与数据库的交互。 Knife4j是一款基于Swagger的API文档生成工具,它提供了更加美观和易用的界面,可以方便地查看和测试API接口。 Swagger是一套用于设计、构建、文档化和使用RESTful风格的Web服务的工具。它可以自动生成API文档,并提供了交互式的界面,方便开发人员进行接口测试和调试。 JWT(JSON Web Token)是一种用于身份验证和授权的开放标准。它通过在用户和服务器之间传递加密的JSON对象来实现身份验证和授权功能,避免了传统的基于Session的身份验证方式带来的一些问题Spring SecuritySpring提供的一个安全框架,它可以集成Spring Boot应用程序中,提供身份验证、授权、攻击防护等安全功能。通过配置Spring Security,我们可以实现对API接口的访问控制和权限管理。 关于Spring Boot + MyBatis Plus + Redis + Driver + Knife4j + Swagger + JWT + Spring Security的Demo,你可以参考以下步骤: 1. 创建一个Spring Boot项目,并引入相应的依赖,包括Spring Boot、MyBatis Plus、Redis、数据库驱动程序等。 2. 配置数据源和数据库驱动程序,以及MyBatis Plus的相关配置,如Mapper扫描路径、分页插件等。 3. 集成Redis,配置Redis连接信息,并使用RedisTemplate或者Jedis等工具类进行操作。 4. 集成Knife4j和Swagger,配置Swagger相关信息,并编写API接口文档。 5. 集成JWTSpring Security,配置安全相关的信息,如登录认证、权限管理等。 6. 编写Controller层的代码,实现具体的业务逻辑。 7. 运行项目,通过Swagger界面进行接口测试。 希望以上内容对你有帮助!如果还有其他问题,请继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值