我正在使用下面的 spring 和 openAPI 依赖项:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
</parent>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>
我的安全配置类定义如下:
@Bean
public UserDetailsService userDetailsService() {
// ensure the passwords are encoded properly
UserDetails userDetails = new User(userName, password, Collections.singleton(new SimpleGrantedAuthority("ROLE_" + ROLE)));
return new InMemoryUserDetailsManager(userDetails);
}
@Bean
@Primary
@ConditionalOnProperty(value = "swagger.auth.enabled", havingValue = "true", matchIfMissing = true)
public static BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
String regexPattern;
if(swaggerAuthEnabled) {
/* Desc: Below regex will hold true for :
* - pattern containing health in its resource
* - pattern if it not contains
* > /actuator/<something>
* > /v2/api-docs
* > /swagger-ui.html
* */
regexPattern = ".*(/health)|^(?!/v2/api-docs|.*/swagger\\-ui\\.html|.*/actuator/).*$";
} else {
regexPattern = ".*";
}
return http.authorizeHttpRequests(authorize -> authorize.requestMatchers(regexPattern)
.permitAll().anyRequest().authenticated())
.httpBasic(Customizer.withDefaults()).build();
}
我添加了类型为:
HTTP
的SecurityScheme和方案:BASIC
我的目标是通过 swagger UI 添加身份验证,工作正常,但我的所有 API 现在也都落后于身份验证,因此我在通过邮递员或其他服务访问它们时收到 401 错误。
我对 OpenAPI 还很陌生,似乎在浏览有关堆栈溢出的所有其他相关解决方案时迷失了方向。
感谢您的帮助!
如果我正确理解你的问题,问题是现在每个请求都必须经过身份验证
.anyRequest().authenticated()
,如果你只想允许任何未经身份验证的请求发送到任何端点,你必须将其更改为.anyRequest().permitAll()