配置两个安全配置时出现未经授权的错误

问题描述

我通过像下面这样扩展 WebSecurityConfigurerAdaptor 来处理两个安全配置

@Configuration
@Order(100)
public class CustomerSecurityAppConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user1")
                .password("{noop}password")
                .and()
                .withUser("user2")
                .password("{noop}password")
                
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors().disable();

        http
                .authorizeRequests()
                .antMatchers("/customers/**")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}

@Configuration
class EmployeeSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("admin")
                .password("{noop}password")
                .roles("USER","ADMIN")
                .and()
                .withUser("user")
                .password("{noop}password")
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors().disable();

        http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"/inventory/**")
                .hasAnyRole("USER","ADMIN")
                .antMatchers(HttpMethod.POST,"/inventory/**")
                .hasRole("ADMIN")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}

这里的想法是有两个 realms。一份用于客户,一份用于订单。当我发出 HTTP 请求时,我收到 200 OK/inventory 端点的 /customers 响应,用户配置为 CustomerSecurityConfiguration 并收到 401 错误两个用户都配置为 EmployeeSecurityConfiguration 配置。我有 inventorycustomers 的两个 REST 端点,带有 GETPOST。 我哪里出错了?

解决方法

我必须为 http 添加请求匹配器,如下所示

    http
       .requestMatchers().antMatchers("/actuator/**")
       .and()
       .authorizeRequests()
       .anyRequest()
       .authenticated()
       .and()
       .formLogin()
       .and()
       .httpBasic();