shiro注解更改角色权限认证方式,和和或

来源:互联网 发布:ipad pro 10.5 知乎 编辑:程序博客网 时间:2024/05/16 12:28

shiro默认的权限认证方式是和方式,比如@RequiresRoles({"admin","devoloper"}) 检查方式需要此时在线的用户同时拥有admin和devoloper两种角色。但有时候咱们只需要用户有其中一种角色就便可以访问,在网上看了一下有许多人都选择继承shiro的过滤器,然后把自己继承的过滤器配置到配置文件,使用自己编写的过滤器来完成角色认证。
其实不需要这么麻烦。在注解方式的源码中有这么一段:

    public void assertAuthorized(Annotation a) throws AuthorizationException {        if (!(a instanceof RequiresRoles)) return;        RequiresRoles rrAnnotation = (RequiresRoles) a;        String[] roles = rrAnnotation.value();        if (roles.length == 1) {            getSubject().checkRole(roles[0]);            return;        }        if (Logical.AND.equals(rrAnnotation.logical())) {            getSubject().checkRoles(Arrays.asList(roles));            return;        }        if (Logical.OR.equals(rrAnnotation.logical())) {            // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first            boolean hasAtLeastOneRole = false;            for (String role : roles) if (getSubject().hasRole(role)) hasAtLeastOneRole = true;            // Cause the exception if none of the role match, note that the exception message will be a bit misleading            if (!hasAtLeastOneRole) getSubject().checkRole(roles[0]);        }    }

从上面的代码中我们可以看出来,有一个叫做Logic的,他可以用来改变角色检验的方式。
在官方的api文档中也有描述:The logical operation for the permission check in case multiple roles are specified. AND is the default
logical操作的默认检查方式是and的。那么我们要如何改变它呢?
其实也很简单:

@RequiresRoles(value = { "admin", "developer" }, logical = Logical.OR)

哈哈哈,感觉讲了一大堆,最后却是一个极其简单的操作。
好吧就这样

原创粉丝点击