首页 > 解决方案 > 在 Spring oauth2 中使用类 ResourceServerConfiguration.configure 中的 HttpSecurity.requestMatchers

问题描述

我一直在努力理解如何以及何时使用HttpSecurity.requestMatchers. 虽然我使用HttpSecurity.requestMatchers但我已经调用authorizeRequestsantMatchers指定安全规则。

我应该什么时候使用

 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,但我仍然不清楚

标签: spring-securityspring-security-oauth2

解决方案


如果您需要HttpSecurity在应用程序中配置多个,那么您通常会使用HttpSecurity.requestMatchers()或替代(但类似)配置选项之一:

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

请参阅6.10 多 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,则WebSecurityConfigurerAdapter不需要配置HttpSecurity.requestMatchers()(或任何替代方案),因为它会自动默认为HttpSecurity.requestMatcher(AnyRequestMatcher.INSTANCE). 所以对于这些配置情况,这就足够了:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(...
    }
}

希望这是有道理的?


推荐阅读