如何使用spring security为特定端点添加HTTP基本身份验证?

dav*_*ave 10 java security spring http

我有一个带Spring Security的Spring Boot应用程序./health要配置新端点,以便可以通过基本HTTP身份验证进行访问.目前的HttpSecurity配置如下:

@Override
protected void configure(HttpSecurity http) throws Exception {

http.requestMatchers()
    .antMatchers(HttpMethod.OPTIONS, "/**")
    .and()
    .csrf()
    .disable()
    .authorizeRequests()
    .anyRequest()
    .permitAll()
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
Run Code Online (Sandbox Code Playgroud)

}

如何为基础身份验证添加/health?我想我需要这样的东西,但我不认为这是完全正确的,我真的不明白在哪里添加它:

    .authorizeRequests()
    .antMatchers(
        // Health status
        "/health",
        "/health/"
    )
    .hasRole(HEALTH_CHECK_ROLE)
    .and()
    .httpBasic()
    .realmName(REALM_NAME)
    .authenticationEntryPoint(getBasicAuthEntryPoint())
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
Run Code Online (Sandbox Code Playgroud)

我发现这些资源很有用,但还不够:

jac*_*646 5

将 Spring Boot 3 与 Spring Security 6 结合使用:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests().requestMatchers("/health/**").authenticated().and().httpBasic()
            .and()
            .authorizeHttpRequests().requestMatchers("/**").permitAll()
            .and()
            .build();
}
Run Code Online (Sandbox Code Playgroud)

这将仅验证下面的端点/health,但使所有其他端点暴露。您需要明确permitAll()安全性未涵盖的端点。