ConfigAttribute

ConfigAttribute的常用组件

  ConfigAttribute作为访问控制模板用于“描述”规则的组件,最常见的方式主要是两种一种是基于注解的一种是基于JavaConfig在Web配置中进行配置的。 其中Spring Security对应方法级的注解主要又可以分为两类: 第一类 @Secured 注解 - secured-annotations 第二类 @PreAuthorize, @PreFilter, @PostAuthorize and @PostFilter - pre-post-annotations

  

WebExpressionConfigAttribute

  WebExpressionConfigAttribute是最常见的访问控制方式,代码形式
 http.authorizeRequests()
        .antMatchers("/").access("hasAnyRole('ANONYMOUS', 'USER')")
        .antMatchers("/login/*").access("hasAnyRole('ANONYMOUS', 'USER')")
        .antMatchers("/logout/*").access("hasAnyRole('ANONYMOUS', 'USER')")
        .antMatchers("/admin/*").access("hasRole('ADMIN')")
        .antMatchers("/events/").access("hasRole('ADMIN')")
        .antMatchers("/**").access("hasRole('USER')")

  基于Web表达是对目标URL的模式进行访问控制,而控制检查的规则最常见两种方式一种是基于角色(Role-Based),另一种是基于表达式(Expressions-Based),以直接使用下面的形式通过角色来达到同样的效果

        .antMatchers("/logout/*").hasAnyRole("USER","ANONYMOUS")

  access还有另外一个功能就是通过表达式将判断的方法委托表达式内的方法进行判断。如果最终表达式返回false则会返回403禁止访问,true则表示授权访问。系统内针对/user路径需要对用户名进行判断,如果用户名不是‘user’则不可以访问。我们把对应判断的代码写在一个CustomWebSecurity的Bean中。

@Component()
public class CustomWebSecurity {
        public boolean check(Authentication authentication) {
            return  (authentication.getName().equals("user"));
        }
}

  通过修改Web表达式我访问控制向/user的路径增加这样一个访问控制的表达式

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/user").access("@customWebSecurity.check(authentication)")
                .and()
                .formLogin();
    }

  

 

posted on 2022-07-31 09:06  溪水静幽  阅读(213)  评论(0)    收藏  举报