How to get Roles from UserPrincipal in Java?
java, servlet-filters, servlets, userprincipal
Solution
From your code, you inject the username and the roles into your `CustomRequestWrapper` in constructor. As you have overriden `getUserPrincipal` in `CustomRequestWrapper` it returns no longer a tomcat `GenericPrincipal` but your anonymous class that only knows to return the name of the user you gave, this via `getName()`. You should try to return a tomcat `GenericPrincipal` through
@Override
public Principal getUserPrincipal()
{
if (this.user == null)
{
return realRequest.getUserPrincipal();
}
// return a forged GenericPrincipal
return new GenericPrincipal(user, "", roles);
}
Alternatively, you could create a custom implementation of Principal knowing about roles.
That will only work if you successfully inject your user and its roles at `CustomRequestWrapper` construction.
Problem
I created a class(Named as CustomRequestWrapper) which is implementing HttpServletRequestWrapper .In CustomRequestWrapper class i am setting user principal.Now in my code i want to get list of roles from the user principal.I tried to use GenericPrincipal Class from tomcat-catalina jar but i am getting casting exception CustomRequestWrapper cannot be cast to GenericPrincipal. Could any one have idea how to get roles from user principal? Note: I am using Apache Tomcat Server Here's my code: ``` public class CustomRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper { public CustomRequestWrapper(String User,List<String> roles,HttpServletRequest request) { super(request); this.user=User; this.roles=roles; this.realRequest=request; headerMap = new HashMap(); } String user; List<String> roles = null; HttpServletRequest realRequest; private Map headerMap; public void addHeader(String name, String value) { headerMap.put(name, new String(value)); } public Enumeration getHeaderNames() { HttpServletRequest request = (HttpServletRequest) getRequest(); List list = new ArrayList(); for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { list.add(e.nextElement().toString()); } for (Iterator i = headerMap.keySet().iterator(); i.hasNext();) { list.add(i.next()); } return Collections.enumeration(list); } public String getHeader(String name) { Object value; if ((value = headerMap.get("" + name)) != null) return value.toString(); else return ((HttpServletRequest) getRequest()).getHeader(name); } @override public boolean isUserInRole(String role) { if (roles == null) { return this.realRequest.isUserInRole(role); } return roles.contains(role); } @override public Principal getUserPrincipal() { if (this.user == null) { return realRequest.getUserPrincipal(); } // make an anonymous implementation to just return our user return new Principal() { public String getName() { return user; } }; } ``` }