Краткая версия:
spring-boot: 2.7.18
spring-doc: 1.8.0
pom Фрагменты .xml:
org.springframework.boot
spring-boot-starter-parent
2.7.18
org.springdoc
springdoc-openapi-ui
1.8.0
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-security
Когда я проверил, самая старая версия Spring Boot для документов Spring была старше Java 1.8.
Фрагменты application.yml:
springdoc:
api-docs:
path: /api-docs/**
swagger-ui:
enabled = true
path = /swagger-ui.html
tryItOutEnabled = false
filter = false
syntaxHighlight.activated = true
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
server:
servlet:
context-path: /api/myservice
Фрагменты SwaggerConfig.java:
@Configuration
public class SwaggerConfig {
@Bean
public GroupedOpenApi api() {
return GroupedOpenApi.builder()
.group("my/package/**")
.pathsToMatch("/**")
.packagesToExclude("/error.**")
.build();
}
@Bean
public OpenAPI apiInfo() {
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(new Components().addSecuritySchemes(
securitySchemeName,
new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.in(SecurityScheme.In.HEADER)
.scheme("bearer")
.bearerFormat("JWT")
))
.info(new Info()
.title(title)
.version(version)
.description("")
)
.servers(Collections.singletonList(
new Server()
.url(contextPath)
.description("Default Server URL")
));
}
}
Фрагменты SpringConfiguration.java:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// I have tried very many things here, but I don't see how it could get much more permissive than this

http
.csrf().disable()
.authorizeRequests().anyRequest().permitAll();
return http
.build();
}
@Bean
public RequestMatcher requestMatcher() {
this.log.debug("Creating request matcher");
List requestMatchers = new ArrayList();
requestMatchers.add(new AntPathRequestMatcher("/**"));
return new OrRequestMatcher(requestMatchers);
}
@Bean
public CustomAuthenticationFilter customAuthenticationFilter(
RequestMatcher requestMatcher,
AuthenticationConfiguration authenticationConfiguration)
throws Exception {
CustomAuthenticationFilter result = new CustomAuthenticationFilter(requestMatcher);
result.setAuthenticationManager(authenticationConfiguration.getAuthenticationManager());
return result;
}
}
Когда я раскомментирую элемент CustomAuthenticationFilter, я получаю сообщение 401 Unauthorized при попадании в localhost/api/myservice/swagger-ui/index.html, потому что этот класс применяется, но когда я его комментирую выходит, я отлично попал на страницу swagger.
Я новичок в этой версии SpringBoot, новичок в Swagger 3 и новичок в Springdocs. У меня это работает в других микросервисах, которые используют FilterRegistrationBean вместо чего-то вроде CustomAuthenticationFilter, и я не уверен, почему те же конфигурации не работают в этом репозитории. Бонусные баллы, если это можно сделать без отключения csrf.
Когда я перехожу к localhost/api/myservice/swagger-ui/index.html, я получаю 401 Unauthorized. Я ожидаю, что страница Swagger загрузится без необходимости авторизации.
Когда я комментирую bean-компонент CustomAuthenticationFilter, я получаю ожидаемый результат. Я не уверен, почему, кроме уверенности в том, что CustomAuthenticationFilter используется для защиты страниц Swagger, хотя я этого не хочу.
Я тоже пробовал
@Bean
public WebSecurityCustomizer webSecurityCustomizer(@Value("${server.servlet.context-path}") String contextPath) {
return web -> web
.ignoring()
.antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**", contextPath + "/swagger-ui/**");
}
который вместо этого выводит на консоль печатные предупреждения об использовании авторизацииHttpRequests. И я тоже это пробовал.
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
//.authorizeHttpRequests()
.antMatchers(
"/v2/api-docs",
"/v3/api-docs/**",
"/swagger-resources/**",
"/swagger-ui/**",
"/swagger-ui.html",
"/swagger-ui/index.html",
contextPath + "/swagger-ui/index.html",
"/configuration/ui",
"/configuration/security",
"/webjars/**",
"/api/**",
contextPath + "/swagger-ui/**"
).permitAll()
.and().authorizeRequests().antMatchers("/api/**").authenticated();
return http.build();
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... n-question