Spring Security multiple url ruleset not working together

后端 未结 1 342
后悔当初
后悔当初 2020-11-30 16:12

I have an HTTP Spring Security configuration that appears to work when I comment out each individual aspect but it doesn\'t work when I combine the Spring Security rules tog

相关标签:
1条回答
  • 2020-11-30 16:18

    You override your previous matchers, see HttpSecurity.html#antMatcher:

    Invoking antMatcher(String) will override previous invocations of mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).

    and HttpSecurity.html#regexMatcher:

    Invoking regexMatcher(String) will override previous invocations of mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).

    If you want more than one configuration of HttpSecurity, see Spring Security Reference:

    We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.

    @EnableWebSecurity
    public class MultiHttpSecurityConfig {
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) { 1
          auth
              .inMemoryAuthentication()
                  .withUser("user").password("password").roles("USER").and()
                  .withUser("admin").password("password").roles("USER", "ADMIN");
      }
    
      @Configuration
      @Order(1)                                                        2
      public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
          protected void configure(HttpSecurity http) throws Exception {
              http
                  .antMatcher("/api/**")                               3
                  .authorizeRequests()
                      .anyRequest().hasRole("ADMIN")
                      .and()
                  .httpBasic();
          }
      }
    
      @Configuration                                                   4
      public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http
                  .authorizeRequests()
                      .anyRequest().authenticated()
                      .and()
                  .formLogin();
          }
      }
    }
    
    0 讨论(0)
提交回复
热议问题