ch11:精确授权——页面级权限控制与方法级权限控制

本节给大家介绍Spring Security精确授权。用户通过认证只是证明了访问者得身法是否合法,但是并未确认其能访问和可执行的动作。精确授权就是对其能够进行哪些操作的细粒度的控制。
页面级精确授权一般是指对页面中的部分元素进行选择性的显示控制,而不是控制整个页面。此外,页面授权只是控制功能的显示与不显示,对于那些绕过界面直接访问服务的行为,还需要方法授权加以保护。Spring Security为我们提供了页面级和方法级两种精确授权。

页面授权主要是通过Jsp标签库在页面添加条件声明来实现

  1. 基于URL控制页面元素
    这种方式主要依据用户权限配置的URL。我们在配置文件中配置了
    .antMatchers("/admin/**").hasRole("ADMIN"),即只有具有ROLE_ADMIN的用户才能访问/admin及其下级页面。当使用以下标签时,Spring Security会根据该配置控制元素的显示。
<sec:authorize url="/admin">
        <h1>通过Url控制访问:</h1>
        <c:out value="/admin"/>
</sec:authorize>

当用户具备能够访问对应URL的角色时,标签内部的元素就会显示。

  1. 基于Spring EL控制页面元素
    当我们没有配置URL与角色关系时,我们可以使用Spring EL表达式控制页面元素的显示。
<sec:authorize access="hasRole('ROLE_ADMIN') and fullyAuthenticated">
        <h1>通过Spring EL控制访问:</h1>
        <c:out value="hasRole('ROLE_ADMIN') and fullyAuthenticated"/>
</sec:authorize>

当用户具备Spring EL描述的角色时,标签内部的元素就会显示。

方法授权主要是通过Annotation或者Java Configuration来实现

  1. Annotation
    在要控制访问的方法上添加注解就可以实现访问控制,前提是方法所在的实例应是Spring的bean。
    在@Configuration之后增加@EnableGlobalMethodSecurity(prePostEnabled = true)注解以开启方法保护,其中prePostEnabled = true标识允许使用@PreAuthorize()注解。在UserService的preAuthorizeMethod方法标记注解,限制只有具备ROLE_ADMIN的用户才能访问该方法,否则系统抛出AccessDeniedException。
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String preAuthorizeMethod() {
        return "This method is protected by Spring Security Annotation.";
    }

通过使用@PreFilter还可以控制集合的元素

    @PostFilter("((filterObject.contains('2') or filterObject.contains('4')) and hasRole('ROLE_USER')) or hasRole('ROLE_ADMIN')")
    public List<String> postFilter() {
        List<String> list = new ArrayList<>();
        for (int index = 0; index < 10; index++) {
            list.add("Item" + index);
        }
        return list;
    }

ROLE_USER角色只能访问集合中的部分元素,而ROLE_ADMIN可以访问全部元素

  1. Java Configuration
    使用Annotation需要我们在每个需要控制的方法上都要增加注解,这样做非常繁杂且不易维护。Spring Security为我们提供了通过Java Configuration的方式控制方法访问的渠道。那么我们就可以通过数据库等方式动态访问权限,简化控制设置。为了实现Java Configuration的方式我们需要多做一些工作。
    创建一个新的类继承GlobalMethodSecurityConfiguration,并且标记@EnableGlobalMethodSecurity。重写方法customMethodSecurityMetadataSource就可以实现对于任意类的任意方法的精确授权。
   @Override
    protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
        MapBasedMethodSecurityMetadataSource metadataSource = new MapBasedMethodSecurityMetadataSource();
        metadataSource.addSecureMethod(UserService.class, "javaConfiguredMethod", SecurityConfig.createList("ROLE_ADMIN"));
        return metadataSource;
    }

该方法至此静态授权,即系统初始化时就确定好方法的访问权限,初始化后不可再修改。查看源代码发现,所有的方法授权都存储在一个Spring bean中,DelegatingMethodSecurityMetadataSource包含所有的静态授权权限。

@Bean
    public MethodSecurityMetadataSource methodSecurityMetadataSource() {
        List<MethodSecurityMetadataSource> sources = new ArrayList<MethodSecurityMetadataSource>();
        ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
                getExpressionHandler());
        MethodSecurityMetadataSource customMethodSecurityMetadataSource = customMethodSecurityMetadataSource();
        if (customMethodSecurityMetadataSource != null) {
            sources.add(customMethodSecurityMetadataSource);
        }
        if (prePostEnabled()) {
            sources.add(new PrePostAnnotationSecurityMetadataSource(attributeFactory));
        }
        if (securedEnabled()) {
            sources.add(new SecuredAnnotationSecurityMetadataSource());
        }
        if (jsr250Enabled()) {
            GrantedAuthorityDefaults grantedAuthorityDefaults =
                    getSingleBeanOrNull(GrantedAuthorityDefaults.class);
            if (grantedAuthorityDefaults != null) {
                this.jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(
                        grantedAuthorityDefaults.getRolePrefix());
            }
            sources.add(jsr250MethodSecurityMetadataSource);
        }
        return new DelegatingMethodSecurityMetadataSource(sources);
    }

如果希望实现动态的授权,可以重新定义该bean("methodSecurityMetadataSource"),扩展MethodSecurityMetadataSource,增加通过数据库等方式获取方法授权的信息即可。

代码示例:https://github.com/wexgundam/spring.security/tree/master/ch11

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容