【发布时间】:2022-12-14 00:37:32
【问题描述】:
我目前正在将我们的 REST 应用程序从 Spring Boot 2.7.5 迁移到 3.0.0-RC2。除了 Open API URL 之外,我希望所有内容都是安全的。在 Spring Boot 2.7.5 中,我们曾经这样做过:
@Named
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/openapi/openapi.yml").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
它工作正常。在 Spring Boot 3 中,我不得不将其更改为
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> requests
.requestMatchers("/openapi/openapi.yml").permitAll()
.anyRequest()
.authenticated())
.httpBasic();
return http.build();
}
}
因为 WebSecurityConfigurerAdapter 已被删除。虽然它不起作用。 Open API URL 也通过基本身份验证得到保护。升级代码时我是否犯了错误,或者这可能是 Spring Boot 3 RC 2 中的问题?
更新由于大多数新 API 已在 2.7.5 中可用,我已将 2.7.5 代码库中的代码更新为以下内容:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests((requests) -> requests
.antMatchers(OPTIONS).permitAll() // allow CORS option calls for Swagger UI
.antMatchers("/openapi/openapi.yml").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
在我们的 3.0.0-RC2 分支中,代码如下:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests((requests) -> requests
.requestMatchers(OPTIONS).permitAll() // allow CORS option calls for Swagger UI
.requestMatchers("/openapi/openapi.yml").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
如您所见,唯一的区别是我调用了 requestMatchers 而不是 antMatchers。此方法似乎已重命名。 antMatchers 方法不再可用。最终效果仍然是一样的。在我们的 3.0.0-RC2 分支上,Spring Boot 要求对 OpenAPI URL 进行基本身份验证。在 2.7.5 上仍然可以正常工作。
【问题讨论】:
-
我可能应该提到我正在使用 Jersey。也许这与它有关?
-
你真的有
"/openapi/openapi.yml"的处理程序(控制器映射)吗?如果没有handler,则解析为not404 NOT_FOUND。这又重定向到/error。由于/error也受到保护,因此它会要求您登录。 -
是的,我愿意。一旦我输入基本身份验证的凭据,就会显示 Open API。
-
可能是匹配器。
requests.antMatchers("/openapi/openapi.yml").permitAll()是不是还是可以的? -
不,我刚刚对问题进行了更新。 antMatchers 方法不再可用。
标签: spring-boot spring-security spring-boot-3