Spring security - 仅在 1 个端点检查身份验证

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

我必须进行以下配置:

@AllArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private ActuatorProperties actuatorProperties;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .passwordEncoder(new BCryptPasswordEncoder())
            .withUser(actuatorProperties.getUser())
            .password(actuatorProperties.getPassword())
            .roles("ACTUATOR");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/actuator/**")
            .hasRole("ACTUATOR")
            .and()
            .httpBasic();
    }
}

如您所见,我只想保护执行器端点并公开其他应用程序端点。但是,当任何基本身份验证通过时,它也会被验证(当提供与执行器不匹配的任何其他基本身份验证时,返回 401)。在我的业务案例中,我将始终有任何基本的身份验证标头,当它不是执行器时我想忽略它(简单地通过)。

我也尝试过类似的事情:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/actuator/**")
            .hasRole("ACTUATOR")
            .antMatchers("/**")
            .permitAll()
            .and()
            .httpBasic();
    }

但这也行不通。

java spring spring-boot spring-security basic-authentication
1个回答
0
投票

您已经很接近了,但这应该适合您的用例:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/actuator/**").hasRole("ROLE_ACTUATOR") 
                .anyRequest().permitAll()
            .and()
            .httpBasic();
    }

请注意,对于 hasRole 方法,需要一个前缀“ROLE_”。我相信您也可以使用

hasAuthority()
方法,并且只能接受没有前缀的定义角色

© www.soinside.com 2019 - 2024. All rights reserved.