使用自定义身份validation筛选器时,使用getRemoteUser()访问用户名

简短版本:当我使用自定义身份validationfilter时,如何让HttpServletRequest.getRemoteUser()返回用户名?

长版:

我正在修改当前使用声明性安全性(web.xml和tomcat-users.xml)的Tomcat应用程序,而不是使用自定义(由我编写)身份validationfilter(从javax.servlet.Filter派生)。 关于如何做到这一点有很多信息,看起来非常简单。

但是,现有的应用程序调用HttpServletRequest.getRemoteUser() ,我假设除非我在我的filter中设置此属性,否则它将返回null。 我找不到有关如何在filter中填充getRemoteUser()属性的任何信息(没有setRemoteUser() )。 我发现那里的post建议将请求对象包装在filter中。 如果必须,我会这样做,但我希望有一种侵入性较小的方法来实现这一目标。

有人可以帮忙吗?

是的,修改HttpServletRequestHttpServletResponse的唯一方法是修饰它,并通过覆盖它们为感兴趣的方法提供自己的实现。 这是带有身份validationfilter的标准模式,这是HttpServletRequestWrapper的目的(响应对应物是HttpServletResponseWrapper )。 我们这样做是为了包装一个kerberized请求,如下所示

 public class KerbHttpServletRequest extends HttpServletRequestWrapper { private Principal myPrincipal; private String myAuthType; public KerbHttpServletRequest(HttpServletRequest aRequest, Principal aPrincipal, String aAuthType) { super(aRequest); myPrincipal = aPrincipal; myAuthType = aAuthType; } /** * This method returns the Remote User name as user\@domain.com. */ @Override public String getRemoteUser() { return myPrincipal.getName(); } @Override public String getAuthType() { return myAuthType; } @Override public Principal getUserPrincipal() { return myPrincipal; } }