我通过以下依赖项将 swagger 集成到了我的 springboot 应用程序中。
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
我还在我的安全配置中允许使用 swagger URL,如下所示:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) {
try {
return http
.requestMatchers(HttpMethod.POST,
"/api/users/register", "/api/users/login").permitAll()
.requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/users/{id}").hasRole("USER")
.requestMatchers(HttpMethod.PUT, "/api/users/{id}").hasRole("USER")
.requestMatchers(HttpMethod.DELETE, "/api/users/{id}").hasRole("USER")
.requestMatchers(HttpMethod.POST, "/api/transactions").hasRole("USER")
.requestMatchers(HttpMethod.GET, "/api/transactions/{id}").hasRole("USER")
.requestMatchers(HttpMethod.PUT, "/api/transactions/{id}").hasRole("USER")
.requestMatchers(HttpMethod.DELETE, "/api/transactions/{id}").hasRole("USER")
)
.build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
以下是我的
application.properties
。
spring.application.name=Fintech-Backend-Developer-Assignment
springdoc.api-docs.path=/api-docs
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
但是当我运行 URL
http://localhost:8080/swagger-ui/index.html
时,我仍然收到以下错误。
您应该在打开开发工具/网络的浏览器中打开“/swagger-ui/index.html”。我相信,您会看到对“/v3/api-docs”的请求失败。默认情况下,这是 openapi 规范生成的文件所在的位置。 Swagger-ui 是根据该文件构建的。由于您不允许匿名访问“/v3/api-docs”,因此 swagger-ui 无法加载。
在这种情况下,您应该在安全配置中允许“/v3/api-docs”以及“/swagger-ui/**”。