1

Once I have a principal logged in, how can I obtain all roles for a user?

I'm creating a Java EE 6 application, and I'm writing a JAX-RS service to return all the roles for the current user, which will be consumed by a front-end to properly render the screen.

I know that there are multiple interfaces that can return whether the user is a member of a certain role, but what I want is a interface that would allow me to get all roles for that particular user.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Bruno Brant
  • 8,226
  • 7
  • 45
  • 90

1 Answers1

1

Given that all the role names are known at compile time, you can do something like the following :

public final class SecurityRoles {

    static final String USER_ROLE = "user";
    static final String ADMIN_ROLE = "admin";
    static final String SUPPORT_ROLE = "support";

}

and

@DeclareRoles({
        USER_ROLE,
        ADMIN_ROLE,
        SUPPORT_ROLE
})
@Path("/rest")
public class SomeRS {

    @Context
    SecurityContext securityContext;

    @GET 
    @PermitAll
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> lookupUserRoles() {
        return Arrays.stream(SomeRS.class.getAnnotation(DeclareRoles.class).value())
                .filter(roleName -> securityContext.isUserInRole(roleName))
                .collect(Collectors.toList());
    }

}

which tests to see if the user is in each of the known roles before adding the role name to a list that is returned.

Note that if you do not use @DeclareRoles then the roles used by the application must be declared in either the web.xml or application.xml files (and you will need to declare the names in a String[] array somewhere).

Steve C
  • 18,876
  • 5
  • 34
  • 37