📅  最后修改于: 2023-12-03 14:47:33.213000             🧑  作者: Mango
Swagger是一个API文档工具,可以使用它来展示和测试Web API。Spring Boot可以通过引入Swagger2插件来创建API文档和测试页面。
打开pom.xml
文件并添加以下依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
在Spring Boot应用程序的主类上添加@EnableSwagger2
注解:
@EnableSwagger2
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
创建一个新的配置类,并添加以下内容:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
启动Spring Boot应用程序并访问http://localhost:8080/swagger-ui/。你将看到所有可用的API列表,并可以测试。
如果你的Spring Boot应用程序使用Spring Security来保护API,你需要执行以下操作才能访问SwaggerUI:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.securitySchemes(Arrays.asList(apiKey()))
.securityContexts(Arrays.asList(securityContext()));
}
private ApiKey apiKey() {
return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
现在您可以访问http://localhost:8080/swagger-ui/ 来查看您的API文档和测试您的API,请注意您需要在登录之前使用JWT或任何其他验证机制进行身份验证,因为SecurityContext配置了API需要全局登录才能访问。
通过简单的添加Maven依赖和几个Swagger配置类,你可以使用Swagger创建和测试API文档。更重要的是,当使用Spring Security来保护API时,还可以通过简单的步骤来允许SwaggerUI访问保护的API。