swagger添加访问密码

文章介绍了如何在项目上线后保护Swagger接口文档,避免直接暴露。通过在SpringBoot中引入相关依赖,配置application.yml文件以启用基本认证,并在Swagger配置类中进行设置,实现只有登录用户才能访问Swagger。同时提到了使用@Profile注解针对不同环境展示或隐藏Swagger。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

swagger现在是很普遍使用的接口文档。

但当项目发布到正式环境之后,swagger暴露给外部是很致命的,因此可以使用添加用户密码访问

(也可以设置swagger隐藏,利用@Profile对不同环境做不同操作,选择展示或者隐藏)

第一步:引入依赖


        <!-- swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
 
        <!--swaggerUI框架-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.4</version>
        </dependency>
        

第二步:编写application.yml文件

swagger:
  production: false
  basic:
    enable: true
    username: root
    password: test

切记swagger.production 不可设置为true,否则将屏蔽所有资源

第三步:编写swagger配置文件文件

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
/**
 * @author wsj
 * @Date 2019/8/20
 */
@EnableSwaggerBootstrapUI//(该注解swagger需要配置登录用户和密码才需要)
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
//                .enable(isEnable)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.test.api"))
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("后台管理系统API")
                .termsOfServiceUrl("http://localhost:8899/")
                .version("1.0")
                .build();
    }
}
@EnableSwaggerBootstrapUI该注解正常使用swagger无需添加,需要用到登录访问时再添加。

如果没有这个注解,加密就不会生效!!!

以上就完成了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值