具有默认的 Spring Security 自动配置,所有请求都受到保护,但有可能排除端点

问题描述 投票:0回答:0

所以我正在为 Spring Boot 应用程序构建一个自动配置,其中包含一些默认配置的特定内容。

默认情况下,所有请求都应该经过身份验证。但是你应该能够拥有一些可以匿名调用的公共方法。

我尝试过不同的东西,我想听听其他人对这些选项的意见,以及对其他选项的建议。

所以图书馆有

WebMvcConfigurer
SecurityFilterChain
配置一些默认规则,但基本上有一个规则
...authorizeHttpRequests().anyRequest().authenticated()...
需要对所有请求进行身份验证。

因此,为了在应用程序本身中自定义此行为,我尝试了两种选择:

选项一

使

SecurityFilterChain
Bean 以最低优先级
@Order(Ordered.LOWEST_PRECEDENCE)
排序,然后让那些使用这个库的人有可能拥有另一个具有最高优先级的
SecurityFilterChain
Bean,允许一些端点。例如(来自使用 Auth 库的应用程序的代码)

@Configuration
public class CustomSecurityConfiguration {
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain custom(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests()
                .requestMatchers("/publicEndpoint").permitAll();
        return http.build();
    }
}

选项2

我修改了库代码并添加了

requestMatchers
来自一些静态源的模式(来自Auth库的代码)

  http
           .authorizeHttpRequests()
           .requestMatchers(PublicEndpoints.ENDPOINTS).permitAll()
           .anyRequest().authenticated()
           ...

我使用自定义注释制作了自定义注释处理器

@AllowAnonymous
,您可以使用它来注释其余控制器中的方法,例如(来自使用 Auth 库的应用程序的代码)

    @GetMapping(path = "publicEndpoint")
    @AllowAnonymous
    public String getPublicMessage() {
        return "Public";
    }

然后使用注释处理器我从上面

PublicEndpoints
生成类静态字符串数组,它将被导入到库本身的
SecurityFilterChain
Bean中的requestMatchers中:

public class PublicEndpoints {
    public static final String[] ENDPOINTS = new String[]{
            "/publicEndpoint"
    };
}

所以基本上我需要两件事:

  1. 对这两个选项的意见。从它的开发方式和使用此 Auth 库的开发人员的角度来看(您更喜欢哪个选项?)
  2. 建议是否可以做得更好

提前致谢。

spring spring-boot spring-mvc spring-security spring-autoconfiguration
© www.soinside.com 2019 - 2024. All rights reserved.