HttpSecurity..authorizeHttpRequests()无法正常工作

ccgok5k5  于 2023-10-20  发布在  Spring
关注(0)|答案(2)|浏览(204)

我需要一个“/public”端点由未经身份验证的用户访问,任何其他端点只能由经过身份验证的用户访问。为什么这个配置不起作用。我根据Spring Security 6授权文档配置了它。当我访问“/public”时,它的响应是401 Unauthorized

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a ->
                a.requestMatchers("/public").permitAll()
                        .anyRequest().authenticated()
                );

        return http.build();
    }
}
cvxl0en2

cvxl0en21#

SecurityFilterChain的配置应该是:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

  @Bean
  SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(a -> {
      a.requestMatchers("/public/**").permitAll(); // for all paths that start with `/public/..`
      a.anyRequest().authenticated();
    });

    return http.build();
  }
}
mzsu5hc0

mzsu5hc02#

这只发生在Spring Security 6.1.2以上的版本中。如果您切换到Sping Boot 3.1.2,您的配置将是正确的,它将工作。

相关问题