将'/' Spring 安全性 6 上不起作用的端点列入白名单



我正在学习Spring Security的相关课程,并尝试在最新的Spring Security 6中使用它。我正试图将localhost:8080/从使用基本认证的认证中列入白名单。但是当我访问URL时,它仍然要求我提供凭据。

目前我有这个bean:

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/").permitAll();
auth.requestMatchers("index").permitAll();
auth.requestMatchers("/css/*").permitAll();
auth.requestMatchers("js/*").permitAll();
auth.anyRequest().authenticated();
}
)
.httpBasic(withDefaults()).build();
}
}

但是默认的/端点,仍然没有被列入白名单。

如果你使用@EnableWebSecurity没有@Configuration在你的类,现在当使用春季安全6,你应该添加@Configuration因为@EnableWebSecurity不再包含@Configuration

Spring Security 6

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import({ WebSecurityConfiguration.class, SpringWebMvcImportSelector.class, OAuth2ImportSelector.class,
HttpSecurityConfiguration.class })
@EnableGlobalAuthentication
public @interface EnableWebSecurity {

参考文献:spring-security/issues/12463

引用@jzheaux:

原因是在6.0中,对所有人都运行授权过滤器调度程序类型,包括FORWARD。这意味着JSP转发到也需要被允许

你可以通过允许forward:

来实现这一点
http.authorizeHttpRequests((authorize) -> authorize
.dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll()
// ... the rest of your authorization rules ) ```

[…]

对我来说,添加

.authorizeHttpRequests((auth) -> {
auth
.shouldFilterAllDispatcherTypes(false)
.requestMatchers("/", "/login", "/privacy-policy", "/legal", "/faq").permitAll()
.anyRequest().authenticated();
})

成功了。

最新更新