mikee
mikee

Reputation: 335

How to programatically obtain roles defined by @DeclareRoles

When deploying a JavaEE application as a WAR file (using the WAS Liberty Profile application server), the mappings between application roles and user groups are defined in server.xml. We have chosen to implement security by means of an EJB bean interceptor that compares the permissions stated on a method annotation with a set of permissions that are assigned to user. This idea is based on an an original article in Java Magazine (Secure Java EE Authentication," Java Magazine, January/February 2013).

To take the idea further, we want to map the roles associated with the user to a more granular set of permissions. Unfortunately there is (currently) no way easy to obtain the list of roles associated with a user. Two suggested methods are proposed in this stack overflow article by @Josh and @Steve.

It struck me that if I can obtain the list of roles defined by the @DeclareRoles() annotation, I could use the request.isUserInRole(role) method for each of these roles without having to maintain a separate list of roles myself.

Has anyone used this method, or are there better methods to implement a finer grained security model since the article was written?

Upvotes: 1

Views: 654

Answers (1)

Steve C
Steve C

Reputation: 19445

Well, you can certainly do something like:

@Stateless
@LocalBean
@DeclareRoles({ ROLE1, ROLE2, ROLE3 })
public class IsCallerInRoleDemoSessionBean {

    @Resource
    private SessionContext sessionContext;

    @PermitAll
    public Set<String> discoverRoles() {
        Set<String> roleNames = new HashSet<>();
        DeclareRoles declaredRoles = IsCallerInRoleDemoSessionBean.class.getAnnotation(DeclareRoles.class);
        for (String roleName : declaredRoles.value())
            if (sessionContext.isCallerInRole(roleName))
                roleNames.add(roleName);
        return roleNames;
    }

}

This is from an old Arquillian Security Demo I did for someone a few years ago.

Ideally, this would also examine super-classes as well.

Upvotes: 2

Related Questions