0

Based on other postings on SO and the web, it would appear that there is no built-in mechanism in a Servlet 3+ container to retrieve the roles from a logged in user, but rather only to check if a user is in a role: request.isUserInRole(String)

But is there any way to retrieve the security-role list as defined for the application?

I find it strange that a LoginModule must persist the principal's credentials but there is nothing defined/related to a principal's roles. At some point, when you call isInRole(), the container must be able to check the list of the user's assigned roles. Is that information not exposed anywhere?

I cannot seem to find any mechanism which allows me to retrieve the defined roles from my deployment descriptor (or via annotations). I'm targeting Wildfly 10/Undertow, but ideally looking for a container agnostic solution.

Is this even feasible? Is there any easy way to programatically retrieve the security-roles defined in my application (either as defined in my descriptor or via @DeclareRoles annotations)?

Community
  • 1
  • 1
Eric B.
  • 23,425
  • 50
  • 169
  • 316
  • http://stackoverflow.com/questions/344117/how-to-get-user-roles-in-a-jsp-servlet ? –  Apr 13 '17 at 17:40
  • @RC. That question doesn't actually answer there question (I actually linked to it in my question). The suggestion there is to either do something that is specific to weblogic, or to build the list of roles manually in the application. But it does not specify if/how to retrieve them from the container. I suspect there must be a mechanism, but not sure which one. – Eric B. Apr 13 '17 at 17:50
  • You could use something like [this post](http://stackoverflow.com/questions/4296910/is-it-possible-to-read-the-value-of-a-annotation-in-java) to read all the annotations. Ultimately though this isn't part of the JEE spec so there isn't a platform agnostic way to get this. There are some possible security ramifications too - should I know all the roles I'm in? Not sure about that but, again, the spec is not helping you here. – stdunbar Apr 13 '17 at 19:21
  • @EricB. maybe, that's why didn't close your question. Note that the accepted answer is not weblogic specific (but might be an overkill I agree) –  Apr 13 '17 at 19:25

1 Answers1

0

For retrieve @rolesAllowed annotation I used introspection. You can do the same to retrieve the defined roles via annotations. Te reference this in the example is a Servlet.

ServletSecurity ss = this.getClass().getAnnotation(ServletSecurity.class);
for (String role : ss.value().rolesAllowed() ) {
        out.print(role + " ");
}

The annotation in the servlet is:

@WebServlet(name = "Coquito", urlPatterns = {"/Coquito"})
@ServletSecurity (@HttpConstraint( rolesAllowed= {"nuevo_menu_intranet"}))
public class Coquito extends HttpServlet {
}