代码之家  ›  专栏  ›  技术社区  ›  Shiva

在类resourceserverconfiguration.configure中使用httpsecurity.requestmatchers在Spring OAuth2中

  •  0
  • Shiva  · 技术社区  · 6 年前

    我一直在努力理解如何以及何时使用 HttpSecurity.requestMatchers . 虽然我用 httpsecurity.requestmatchers 但我有电话 authorizeRequests antMatchers 指定安全规则。

    我什么时候用

     http.requestMatchers()
                  .antMatchers("/secure/**","/patients/**","/patient/**", "/hello/**")
                  .and()
                  .authorizeRequests().antMatchers("/secure/**","/books/**","/book/**", "/hello/**")
                  .hasAnyRole("ADMIN","USER");
    

    结束

          http
          .authorizeRequests().antMatchers("/secure/**","/books/**","/hello/**", "/hello/**")
          .hasAnyRole("ADMIN","USER");
    

    一个场景可以帮助我理解 httpsecurity.requestmatchers

    我确实调查了 requestMatchers 但我还是不清楚

    1 回复  |  直到 6 年前
        1
  •  1
  •   Joe Grandja    6 年前

    如果需要配置多个 HttpSecurity 在您的应用程序中, HttpSecurity.requestMatchers() 或其他(但类似)配置选项之一:

    • HttpSecurity.requestMatcher(RequestMatcher)
    • HttpSecurity.antMatcher(String)
    • HttpSecurity.mvcMatcher(String)
    • HttpSecurity.regexMatcher(String)

    参考文献见 6.10 Multiple HttpSecurity

    例如,如果应用程序在基本路径上有一组API的根 /api 以及应用程序的管理部分的另一类终结点,根位于基路径 /admin 比你可能定义的2x WebSecurityConfigurerAdapter 对于您的申请:

    @EnableWebSecurity
    public class SecurityConfig {
    
        @Configuration
        @Order(1)
        public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .requestMatchers()
                        .antMatchers("/api/**")
                        .and()
                    .authorizeRequests()
                        .antMatchers("/api/endpoint1")
                            .hasRole("USER1");
            }
        }
    
        @Configuration
        public static class AdminWebSecurityConfig extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .requestMatchers()
                        .antMatchers("/admin/**")
                        .and()
                    .authorizeRequests()
                        .antMatchers("/admin/endpoint1")
                            .hasRole("ADMIN1");
    
            }
        }
    }
    

    但是,如果您只提供1X Web安全配置适配器 不需要配置 httpsecurity.requestMatchers()。 (或任何备选方案),因为它将自动默认为 HttpSecurity.requestMatcher(AnyRequestMatcher.INSTANCE) .因此,对于这些配置情况,这就足够了:

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers(...
        }
    }
    

    希望这是合理的?