3.5 请求授权(Authorize Requests)

2016-06-11 13:14:21 50,547 2

我们的案例目前使用的是WebSecurityConfigurerAdapter中默认的HttpSecurity对象的配置,该配置是要求应用中所有url的访问都需要进行验证。我们也可以自定义哪些URL需要权限验证,哪些不需要。只需要在我们的SecurityConfig类中覆写configure(HttpSecurity http)方法即可。

protected void configure(HttpSecurity http ) throws Exception {
             http
                  .authorizeRequests()            1                                                   
                        .antMatchers( "/resources/**", "/signup" , "/about").permitAll()  2
                        .antMatchers( "/admin/**").hasRole("ADMIN" )                    3    
                        .antMatchers( "/db/**").access("hasRole('ADMIN') and hasRole('DBA')")  4
                        .anyRequest().authenticated()        5
                                         
                        .and()
                   // ...
                  .formLogin();
      }

1、http.authorizeRequests()方法有很多子方法,每个子匹配器将会按照声明的顺序起作用。

2、指定用户可以访问的多个url模式。特别的,任何用户可以访问以"/resources"开头的url资源,或者等于"/signup"或about

3、任何以"/admin"开头的请求限制用户具有 "ROLE_ADMIN"角色。你可能已经注意的,尽管我们调用的hasRole方法,但是不用传入"ROLE_"前缀

4、任何以"/db"开头的请求同时要求用户具有"ROLE_ADMIN"和"ROLE_DBA"角色。

5、任何没有匹配上的其他的url请求,只需要用户被验证。


源码解读

在这个案例中我们调用了antMatchers方法来定义什么样的请求可以放过,什么样的请求需要验证。antMatchers使用的是Ant风格的路径匹配模式(在下一节我们会详细讲解)。这个方法中定以在AbstractRequestMatcherRegistry中,我们查看一下这个方法的源码:

public C antMatchers(String... antPatterns) {
   return chainRequestMatchers(RequestMatchers.antMatchers(antPatterns));
}

这个方法内部又调用了RequestMatchers对象的静态方法antMatchers方法,源码如下

public static List<RequestMatcher> antMatchers(HttpMethod httpMethod,
      String... antPatterns) {
   String method = httpMethod == null ? null : httpMethod.toString();
   List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
   for (String pattern : antPatterns) {
      matchers.add(new AntPathRequestMatcher(pattern, method));
   }
   return matchers;
}

可见最终返回的是一个RequestMatcher列表,事实上,SpringSecurity在工作过程中,就可以利用RequestMatcher对象来进行路径匹配了。

除了ANT风格的路径匹配模式,我们还可以使用基于正则表达式的路径匹配模式,对应的方法是regexMatchers(..)。