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

cig3rfwq  于 2023-04-28  发布在  Spring
关注(0)|答案(2)|浏览(176)

我有一个带有Spring Security的Sping 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);

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

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

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

mkshixfv

mkshixfv1#

解决方案是实现多种配置,如下所述: www.example.com
编辑2021-12-11:
存档参考链接: www.example.com
这里有一个类似的问题链接到一个例子:https://stackoverflow.com/a/18864786/1568224

gpfsuwkq

gpfsuwkq2#

使用Sping 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();
}

这将仅对/health下的端点进行身份验证,但会暴露所有其他端点。您需要在安全性未覆盖的端点上显式地permitAll()

相关问题