Springboot+Spring Security+Swagger2.9.2:完美整合——亲测通过(2020.6)

前言

Swagger2本身没有什么难点,配置简单、操作方便,实为居家旅行、公干私活必备神器。世人多爱之,山人也概莫能外。然在Spring Security的安全大网之下,二者经常打架,有你无我,水火不容,关系很不融洽。程序猿与程序媛苦此久矣。尝求诸于互联网,则众说纷纭,莫衷一是。忽一日,终得解,抚掌大笑,原来如此。是以山人写此过程,助拳于困厄之辈,贻笑于大方之家。
是为记。

开发环境

1. Springboot:2.2.5
2. Swagger:2.9.2
3. Spring Security:5.2.2

一、引入依赖

 <project>
    <properties>
        <java.version>1.8</java.version>
        <springfox-swagger2.version>2.9.2</springfox-swagger2.version>
        <springfox-swagger-ui.version>2.9.2</springfox-swagger-ui.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        ...

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-swagger-ui.version}</version>
        </dependency>
    </dependencies>
</project>

二、SwaggerConfig配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig  {

    @Value("${swagger.enable}")
     private boolean swaggerEnable;  
     //是否允许显示swagger。此值可在application.properties中设定。
     //作为开关,可在生产环境和开发环境打开或关闭,简便易行。

     @Bean
      public Docket docket(){

          return new Docket(DocumentationType.SWAGGER_2)
                  .enable(swaggerEnable)
                  .select()
                  .apis(RequestHandlerSelectors.basePackage("com.ccc.huxin.controller.open"))
                  .paths(PathSelectors.any())
                  .build().apiInfo(new ApiInfoBuilder()
                          .description("XXXX开发文档(XX软件)")
                          .contact(new Contact("XX软件","http://xxx.com.cn","xxxx@163.com"))
                          .version("V2.0")
                          .title("Api开发文档")
                          .license("Apache2.0")
                          .build());
      }


}

三、Spring Security配置类

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()

                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/v2/*").permitAll()
                .antMatchers("/csrf").permitAll()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                。。。



 }                 

}

四、测试案例

写一个ctrolller测试一下:

 @Controller
@RequestMapping(value = "/open/mail")
@Api(tags = "邮件发送")
public class MailController {
   
  @ResponseBody
  @RequestMapping(value = "/163/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  @ApiOperation(value = "邮件添加",notes = "传入要发送的邮件")
  @ApiResponses({
          @ApiResponse(code = 1,message = "ok"),
          @ApiResponse(code = 2,message = "error"),
  })
   public String sendHtmlMail(HttpServletRequest request){
       ...
       ...


}

五、最后成果

如此,二者完美兼容,在不损伤安全性的前提下,可以开放指定的ctrtroller给用户访问。并可结合系统参数(swagger.enable=false),随时关闭此接口访问权限。

在application.properties中设定:

#允许访问 接口开发文档  
swagger.enable=true

测试:
http://localhost:8081/swagger-ui.html#/
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值