views:

265

answers:

1

I was wondering if it would be possible to retrieve the complete list of security roles defined in a web.xml file in the java code? And if so how to do it?

I am aware of the 'isUserInRole' method but I also want to handle cases where a role is requested but not defined (or spelled differently) in the web.xml file.

+2  A: 

As far as I know, there's no way do do this within the Servlet API. However, you can parse web.xml directly and extract the values yourself. I used dom4j below, but you can use whatever XML processing stuff you like:

protected List<String> getSecurityRoles() {
 List<String> roles = new ArrayList<String>();
 ServletContext sc = this.getServletContext();
 InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");

 try {
  SAXReader reader = new SAXReader();
  Document doc = reader.read(is);

  Element webApp = doc.getRootElement();

  // Type safety warning:  dom4j doesn't use generics
  List<Element> roleElements = webApp.elements("security-role");
  for (Element roleEl : roleElements) {
   roles.add(roleEl.element("role-name").getText());
  }
 } catch (DocumentException e) {
  e.printStackTrace();
 }

 return roles;
}
Ian McLaird
too bad the container offers no way to get that info, but this seems like a fine workaround. Thanks!
Jasper