views:

4115

answers:

2

Hi,

Is there any way to get a String[] with the roles a user has in the JSP or Servlet?

I know about request.isUserInRole("role1") but I also want to know all the roles of the user.

I searched the servlet source and it seems this is not possible, but this seems odd to me.

So... any ideas?

A: 

The answer is messy.

First you need to find out what type request.getUserPrincipal() returns in your webapp.

    System.out.println("type = " + request.getUserPrincipal().getClass());

Let's say that returns org.apache.catalina.realm.GenericPrincipal.

Then cast the result of getUserPrincipal() to that type and use the methods it provides.

    final Principal userPrincipal = request.getUserPrincipal();
    GenericPrincipal genericPrincipal = (GenericPrincipal) userPrincipal;
    final String[] roles = genericPrincipal.getRoles();

I said it was going to be messy. It's not very portable either.

Steve McLeod
It returns class org.jboss.security.SimplePrincipal and that class doesn't have getRoles()... which is very stupid...Sorry, I should have mentioned: I'm using JBoss 4.2.3GA AS
AlfaTeK
A: 

Read in all the possible roles, or hardcode a list. Then iterate over it running the isUserInRole and build a list of roles the user is in and then convert the list to an array.

String[] allRoles = {"1","2","3"};
HttpServletRequest request = ... (or from method argument)
List userRoles = new ArrayList(allRoles.length);
for(String role : allRoles) {
 if(request.isUserInRole(role)) { 
  userRoles.add(role);
 }
}

// I forgot the exact syntax for list.toArray so this is prob wrong here
return userRoles.toArray(String[].class);
Josh
Yes, I can do this when the user does the login... That's a nice hack.But still, is this impossible to do in JBoss like userPrincipal.getRoles(); ?
AlfaTeK
When it comes to writing webapps, I always avoid any of the server-specific code. You want to maintain portability across servers like Tomcat and Resin and Jetty. So you would need to see if there is something in the spec, or a way to retrieve the list from the context.
Josh