SpringBoot - 集成Swagger2、Knife4j接口文檔/升級(jí)版swagger-bootstrap-ui配置以及賬號(hào)密碼登錄
pom引入
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>1.9.6</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--原生swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
配置類SwaggerConfig
package your.package.config;
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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("your.package.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* API 說明,包含作者、簡(jiǎn)介、版本、host、服務(wù)URL
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("XXXAPI文檔")
.description("XXXAPI文檔")
//.contact(new Contact("API文檔", "http://www.XXX.com/", "xxx@qq.com"))//作者信息
//.version("1.0")//定義api 版本號(hào)
.build();
}
}
請(qǐng)注意@Configuration和@EnableSwagger2注解。這兩個(gè)注解分別表示這是一個(gè)配置類,以及啟用了Swagger 2。只有在這兩個(gè)注解都存在的情況下,Swagger才會(huì)被正確啟用。
如果您的項(xiàng)目使用的是Swagger 3(即OpenAPI 3),則配置文件可能如下所示:
package your.package.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.select()
.apis(RequestHandlerSelectors.basePackage("your.package.controller"))
.paths(PathSelectors.any())
.build();
}
}
訪問http://localhost:8080/swagger-ui.html
(假設(shè)項(xiàng)目運(yùn)行在8080端口)應(yīng)該可以看到Swagger UI。如果您的項(xiàng)目使用的是OpenAPI 3,訪問http://localhost:8080/swagger-ui/index.html
。
啟動(dòng)項(xiàng)目
訪問http://localhost:8080/swagger-ui.html
訪問http://localhost:8080/doc.html
賬號(hào)密碼登錄
現(xiàn)有需求,/swagger-ui.html 頁面需要添加登錄認(rèn)證,但是本來的接口不需要登錄認(rèn)證
一、使用http://localhost:8080/swagger-ui.html路徑訪問,設(shè)置賬號(hào)密碼登錄:
為Swagger UI添加登錄權(quán)限,我使用Spring Security來實(shí)現(xiàn)。首先,確保您已經(jīng)在項(xiàng)目中添加了Spring Security依賴。在pom.xml文件中添加以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
從application.yml文件中讀取用戶名和密碼
# 自定義swagger登錄攔截,攔截路徑swagger-ui.html和/doc.html
custom-swagger-security:
basic:
enabled: false
path: /swagger-ui.html
user:
name: admin #賬號(hào)
password: 123456 #密碼
接下來,創(chuàng)建一個(gè)配置類來配置Spring Security。在src/main/java/your/package/config目錄下,創(chuàng)建一個(gè)名為SecurityConfig.java的文件,并添加以下內(nèi)容:
package your.package.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${security.user.name}")
private String username;
@Value("${security.user.password}")
private String password;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/swagger-ui.html").authenticated()
//.antMatchers(HttpMethod.GET, "/webjars/**", "/swagger-resources/**", "/v2/api-docs").permitAll()
.anyRequest().permitAll()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(username)
.password("{noop}" + password)
.roles("USER");
}
}
這個(gè)配置類繼承了WebSecurityConfigurerAdapter,并覆蓋了configure(HttpSecurity http)和configure(AuthenticationManagerBuilder auth)方法。在configure(HttpSecurity http)方法中,我們配置了對(duì)/swagger-ui.html的訪問需要認(rèn)證,同時(shí)允許訪問其他必要的資源。
在configure(AuthenticationManagerBuilder auth)方法中,我們?cè)O(shè)置了一個(gè)內(nèi)存中的用戶(admin)和密碼(123456)。這里我們使用了明文密碼,但在實(shí)際生產(chǎn)環(huán)境中,請(qǐng)確保使用加密的密碼。
在Spring Security 5中,可以使用"{noop}"前綴來表示不對(duì)密碼進(jìn)行加密。這將告訴Spring Security使用NoOpPasswordEncoder來處理密碼。將此前綴添加到SecurityConfig.java中的.password()方法中,可以解決 "There is no PasswordEncoder mapped for the id 'null'" 錯(cuò)誤。
請(qǐng)注意,這種方法不建議在生產(chǎn)環(huán)境中使用,因?yàn)樗话踩?。在生產(chǎn)環(huán)境中,您應(yīng)該使用一個(gè)安全的密碼編碼器,例如 BCryptPasswordEncoder。
現(xiàn)在,當(dāng)您訪問http://localhost:8080/swagger-ui.html時(shí),瀏覽器會(huì)要求您輸入用戶名和密碼。只有在輸入正確的用戶名和密碼后,您才能訪問Swagger UI。
二、使用http://localhost:8080/doc.html路徑訪問,設(shè)置賬號(hào)密碼登錄:
knife4j相比swagger-ui更加強(qiáng)大,針對(duì)Swagger的資源接口,Knife4j提供了簡(jiǎn)單的Basic認(rèn)證功能,個(gè)人覺得文檔頁面樣式也更加簡(jiǎn)潔明了
1、yml中添加配置
knife4j:
# 開啟增強(qiáng)配置
enable: true
# 開啟生產(chǎn)環(huán)境屏蔽,配置此屬性為true,所有資源都會(huì)屏蔽輸出.
production: false
# 開啟Swagger的Basic認(rèn)證功能,默認(rèn)是false
basic:
enable: true
# Basic認(rèn)證用戶名
username: admin
# Basic認(rèn)證密碼
password: 123456
2、在swagger-ui基礎(chǔ)上只是多了@EnableSwaggerBootstrapUi
類注解
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUi
public class SwaggerConfig implements WebMvcConfigurer {
}
訪問效果:
注意
:
knife4j:
# 開啟增強(qiáng)配置
enable: true
# 開啟生產(chǎn)環(huán)境屏蔽
production: true
配置此屬性后,所有資源都會(huì)屏蔽輸出.
效果圖如下:
調(diào)整
由于http://localhost:8080/swagger-ui.htm和http://localhost:8080/doc.htm都需要登錄配置。
為了做統(tǒng)一權(quán)限驗(yàn)證,所以此處實(shí)現(xiàn)方法如下:
1、yml中配置如下
# 自定義swagger登錄攔截,攔截路徑swagger-ui.html和/doc.html
custom-swagger-security:
basic:
enabled: false
path: /swagger-ui.html
user:
name: admin #賬號(hào)
password: 123456 #密碼
修改
package your.package.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Security配置攔截
* 1、開啟swagger-ui.html原生頁面認(rèn)證
* @author chenp
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${custom-swagger-security.basic.enabled:false}")
private boolean basicEnabled;
@Value("${custom-swagger-security.basic.path}")
private String basicPath;
@Value("${custom-swagger-security.user.name}")
private String username;
@Value("${custom-swagger-security.user.password}")
private String password;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable(); // Disable CSRF protection for simplicity
if (basicEnabled) {
http.authorizeRequests()
// swagger頁面需要添加登錄校驗(yàn)
.antMatchers(HttpMethod.GET, "/swagger-ui.html", "/doc.html").authenticated() // Require authentication for Swagger UI
//其他請(qǐng)求全部允許
.anyRequest().permitAll() // Allow all other requests
.and()
.httpBasic(); // Enable basic authentication
} else {
http.authorizeRequests()
.anyRequest().permitAll();
}
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
// Use clear text password for simplicity, but don't use it in production
//.password("{noop}" + password)
//{noop}是使用明文密碼,不進(jìn)行加密,不建議使用在生產(chǎn)環(huán)境,在生產(chǎn)環(huán)境中,使用一個(gè)安全的密碼編碼器,例如 BCryptPasswordEncoder
.password(passwordEncoder().encode(password))
.roles("USER");
}
}
ps:此處對(duì){noop}密碼編碼器改為使用一個(gè)安全的密碼編碼器,例如 BCryptPasswordEncoder
加強(qiáng)版swagger-bootstrap-ui配置
swagger-bootstrap-ui相比swagger-ui更加強(qiáng)大,提供測(cè)試及賬號(hào)密碼驗(yàn)證登錄等配置,個(gè)人覺得文檔頁面樣式更加簡(jiǎn)潔明了
配置方式基本與swagger-ui一致
1、pom依賴
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
2、添加配置類SwaggerConfig:在swagger-ui基礎(chǔ)上只是多了@EnableSwaggerBootstrapUI類注解
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;
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.XXX.web.controller"))//掃描包范圍
.paths(PathSelectors.any())
.build();
}
/**
* API 說明,包含作者、簡(jiǎn)介、版本、host、服務(wù)URL
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("XXXAPI文檔")
.description("XXXAPI文檔")
//.contact(new Contact("API文檔", "http://www.XXX.com/", "xxx@qq.com"))//作者信息
//.version("1.0")//定義api 版本號(hào)
.build();
}
}
注
:如果有登錄驗(yàn)證等攔截器,如下資源需要放行
@Component
public class MyInterceptorConfigure extends WebMvcConfigurationSupport { //WebMvcConfigurer
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// excludePathPatterns 用戶排除攔截
String[] excludePathPatterns = { "/swagger-ui.html/**","/swagger-resources/**","/webjars/**","/v2/**"};
registry.addInterceptor(userTokenInterceptor).addPathPatterns("/**").excludePathPatterns(excludePathPatterns);
super.addInterceptors(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
3:yml配置文件添加接口文檔訪問自定義賬號(hào)密碼
#配置swagger登陸驗(yàn)證
swagger:
production: false
basic:
enable: true
username: admin
password: 123456
4、修改攔截器等放行資源
主要修改:
String[] excludePathPatterns = { "/doc.html/**","/swagger-resources/**","/webjars/**","/v2/**"};
@Component
public class MyInterceptorConfigure extends WebMvcConfigurationSupport { //WebMvcConfigurer
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// excludePathPatterns 用戶排除攔截
String[] excludePathPatterns = { "/doc.html/**","/swagger-resources/**","/webjars/**","/v2/**"};
registry.addInterceptor(userTokenInterceptor).addPathPatterns("/**").excludePathPatterns(excludePathPatterns);
super.addInterceptors(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
訪問地址文章來源:http://www.zghlxwxcb.cn/news/detail-716315.html
localhost:8080/doc.html
資源參考
https://doc.xiaominfo.com/docs/features/accesscontrol
swagger配置及升級(jí)版swagger-bootstrap-ui配置+訪問賬號(hào)密碼登錄限制
直接使用security.basic.path無效|——springboot2.0以上的security的配置
SpringBoot - 集成Swagger、Knif4j接口文檔以及文檔添加賬號(hào)密碼登錄
Swagger設(shè)置密碼登錄
Spring Boot整合Swagger3.0及Knife4j文章來源地址http://www.zghlxwxcb.cn/news/detail-716315.html
到了這里,關(guān)于SpringBoot - 集成Swagger2、Knife4j接口文檔/升級(jí)版swagger-bootstrap-ui配置以及賬號(hào)密碼登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!