Spring 安全性 - 执行器端点的自定义身份验证提供程序和 HTTP Basic

Spring Security - Custom Authentication Provider and HTTP Basic for Actuator Endpoints

我有一个 运行 Spring 启动应用程序(Spring Boot v2.4.1),我想使用 Spring Boot Admin 监控它。

我已经设置了服务器,我可以使用不安全的 /actuator/ 端点监控我的应用程序实例。我上面有一个 permitAll()

现在我想保护它,但我不知道如何在不破坏我当前的安全配置的情况下做到这一点。

我已将 Spring 安全配置为匹配数据库中的 用户名 密码 以及 CustomAuthenticationProvider。如果可能的话,我想添加一个带有 HTTP 基本身份验证的执行器端点。

这是我当前的安全配置:

http.
            authorizeRequests()
            .antMatchers("/admin/**").hasAuthority(AUTHORITY_ADMIN)
            .antMatchers("/user/**").hasAnyAuthority(AUTHORITY_ADMIN, AUTHORITY_USER)
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error=true")
            .successHandler(new CustomUrlAuthenticationSuccessHandler(translator))
            .usernameParameter("username")
            .passwordParameter("password")
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/")
            .and()
            .exceptionHandling().accessDeniedPage("/403")
            .and()
            .headers().frameOptions().sameOrigin();

我想保留该配置并告诉 spring 每当用户点击 /actuator/ 端点时,它将需要 HTTP 基本安全凭证。

我正在考虑拥有两个 @Configuration 类,扩展 WebSecurityConfigurerAdapter。一个是我已经得到的,另一个是用于执行器端点的。但是我没有运气。

谢谢

非常感谢

您可以创建两个 SecurityFilterChain bean,一个用于您的 /actuator/** 优先级较高的端点,另一个用于所有其他优先级较低的端点,如下所示:

@Bean
@Order(1)
public SecurityFilterChain actuatorWebSecurity(HttpSecurity http) throws Exception {
    http.requestMatchers((matchers) -> matchers
        .antMatchers("/actuator/**"));
    http.authorizeRequests((authz) -> authz
        .anyRequest().authenticated());
    http.httpBasic();
    http.userDetailsService(myUserDetailsService);
    ...
    return http.build();
}

@Bean
@Order(2)
public SecurityFilterChain defaultWebSecurity(HttpSecurity http) throws Exception {
    // your current configuration
}

在此配置中,@Order 注释告诉顺序 SecurityFilterChain 将与请求匹配。

我是这样解决的:我创建了一个新的 @Configuraiton class 扩展 WebSecurityConfigurerAdapter,

我无法停止使用 WebSecurityConfigurerAdapter(正如@Marcus-Hert-da-Coregio 在评论中所建议的那样),因为如果我不扩展它,我将无法定义我的自定义 AuthenticationProvider.

此 class 具有 @Order(1),因此它将优先于我的其他初始配置(我将其设置为 @Order(2))。这是它的内容:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/actuator/**")
                .csrf().disable()
                .authorizeRequests()
                    .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

然后我的自定义 AuthenticationProvider 将验证用于访问执行器端点的给定凭据是否有效。

附加信息

我第一次测试失败的原因是因为我没有设置初始值

.antMatcher("/actuator/**")

通过添加它,我告诉 SpringSecurity 这个配置应该只应用于那些端点。我从 this article

得到这个概念

我希望这对以后的人有所帮助