authorizeRequests() 与authorizeHttpRequests?(Customizer<AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry>

cha*_*lin 11 spring spring-security

我想配置我的 Spring 应用程序安全性,所有请求都应在提供服务之前进行身份验证。

所以我创建了一个过滤器链 bean:

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        return http
            .authorizeRequests().anyRequest().authenticated()
            .and().formLogin()
            .and().build();
    }
Run Code Online (Sandbox Code Playgroud)

我还发现authorizeRequests方法有一个重载版本,它接受定制器接口参数。所以我尝试了参数化版本。

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        return http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests.anyRequest().authenticated()
            )

            .formLogin()
            .and().build();
    }
Run Code Online (Sandbox Code Playgroud)

我注意到参数化的authorizeRequests方法将返回相同的HttpSecurity对象,因此您可以继续配置而无需调用and()。

这是他们之间唯一的区别吗?如果真是这样,这个重载版本岂不是显得多余了吗?

Mar*_*gio 18

两种声明方式authorizeRequests均有效。接受定制器的方法是使代码更易于阅读的一种方法,因为它避免了多个缩进级别。建议使用 lambda 定制器。

authorizeRequests和之间的区别authorizeHttpRequests解释如下。使用authorizeHttpRequests新的简化AuthorizationManagerAPI 和AuthorizationFilter,而authorizeRequests使用AccessDecisionManagerFilterSecurityInterceptor。后者将在 Spring Security 的未来版本中被弃用。