Search code examples
shiro

How can I ask apache shiro about object ids


Given a subject that has the following permissions:

printer:1:manage  
printer:2:manage  
printer:3:admin  
printer:1:print
printer:4:print

I know I can ask if:

subject.isPermitted('printer:1:manage') 

But how do i ask shiro questions such as:

  • For which printer id's does the subject has a "manage" permission? (I want the answer 1,2)

  • For which printer id's does the subject has a permission (or any kind)? (I want the answer 1,2,3)

  • For which printer id's does the subject has a manage or admin permission? (I want the answer 1,4)


Solution

  • Apache Shiro's API only provides checks and assertions for permissions or roles; it does not provide any finder methods to look up what a Subject has permissions to, or to look up which Subjects have permission to something.

    You could explore implementing your own findPermissions() in your AuthorizingRealm that takes a query permission and collects all available permissions for the Subject where queryPermission.implies(grantedPermission) returns true, somewhat along these lines:

    protected Collection<Permission> findPermissions(Permission queryPermission, AuthorizationInfo info) {
        Collection<Permission> foundPermissions;
        Collection<Permission> perms = getPermissions(info);
    
        if (perms != null && !perms.isEmpty()) {
            foundPermissions = new ArrayList<Permission>();
            for (Permission perm : perms) {
                if (queryPermission.implies(perm)) {
                    foundPermissions.add(perm);
                }
            }
        }
        else {
            foundPermissions = Collections.emptyList();
        }
    
        return foundPermissions;
    }
    

    Note that this is the inverse implies relationship to how AuthorizingRealm.isPermitted() performs its check.

    If you aren't committed to Apache Shiro, yet, the open-source OACC security framework (disclosure: I'm maintainer and co-author) actually features efficient symmetric query methods to find both the permissions on resources, as well as which resources have permission to something, without you having to implement anything.