我创建了一个类(名为 CustomRequestWrapper ),该类正在实现 HttpServletRequestWrapper 。在 CustomRequestWrapper 类中,我正在设置用户主体。现在在我的代码中,我想从用户主体中获取角色列表。我尝试使用GenericPrincipal来自 tomcat-catalina jar的类,但是我遇到强制转换异常 CustomRequestWrapper 无法强制转换为 GenericPrincipal 。谁能想到如何从用户主体中获取角色?

注意:我正在使用Apache Tomcat服务器

这是我的代码:

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;
        }
    };
}

}

最佳答案

从代码中,将用户名和角色注入构造函数中的CustomRequestWrapper中。当您在getUserPrincipal中覆盖了CustomRequestWrapper时,它不再返回tomcat GenericPrincipal,而是您的匿名类,该类仅通过getName()返回您给定的用户名。您应该尝试通过以下方式返回tomcat GenericPrincipal

  @Override
  public Principal getUserPrincipal()
  {
    if (this.user == null)
    {
      return realRequest.getUserPrincipal();
    }

    // return a forged GenericPrincipal
    return new GenericPrincipal(user, "", roles);
  }

或者,您可以创建一个了解角色的Principal的自定义实现。

仅当您在CustomRequestWrapper构造中成功注入用户及其角色时,这才起作用。

10-08 01:14