使用自定义身份验证筛选器时,使用getRemoteUser()访问用户名 [英] Accessing username with getRemoteUser() when using custom authentication filter
问题描述
简短版本:当我使用自定义身份验证过滤器时,如何获取 HttpServletRequest.getRemoteUser()
以返回用户名?
Short version: How do I get HttpServletRequest.getRemoteUser()
to return the username when I am using a custom authentication filter?
长版本:
我正在修改当前使用声明性安全性(web.xml& tomcat-users.xml)的Tomcat应用程序来代替使用自定义(由我编写)身份验证过滤器(从javax.servlet.Filter派生)。关于如何执行此操作有很多信息,它看起来非常简单。
I am modifying a Tomcat application that currently uses declarative security (web.xml & tomcat-users.xml) to instead use a custom (written by me) authentication filter (derived from javax.servlet.Filter). There is a lot of information out there on how to do this and it looks very straightforward.
但是,现有应用程序调用 HttpServletRequest。 getRemoteUser()
,我假设除非我在我的过滤器中设置此属性,否则它将返回null。我找不到有关如何在过滤器中填充 getRemoteUser()
属性的任何信息(没有 setRemoteUser()
)。我找到了推荐包装的发布在那里过滤器中的请求对象。如果必须,我会这样做,但我希望有一种侵入性较小的方法来实现这一点。
However, the existing application makes calls to HttpServletRequest.getRemoteUser()
, and I assume that unless I do something to set this property in my filter, it will return null. I cannot find any information on how to populate the getRemoteUser()
property in a filter (there is no setRemoteUser()
). I found a post out there that recommends wrapping the request object in the filter. I will do this if I have to, but I am hoping there is a less invasive way to accomplish this.
任何人都可以帮忙吗?
推荐答案
是的,修改 HttpServletRequest
或 HttpServletResponse $的唯一方法c $ c>是装饰它,并通过覆盖它们为感兴趣的方法提供自己的实现。这是带有身份验证过滤器的标准模式,这是
HttpServletRequestWrapper
的目的(响应对应的是 HttpServletResponseWrapper
)。我们通过这种方式来包装一个kerberized请求,如下所示
Yes, the only way to modify an HttpServletRequest
or HttpServletResponse
is to decorate it and provide your own implementation for the methods of interest by overriding them. This is a standard pattern with authentication filters and that is the purpose of HttpServletRequestWrapper
(the response counterpart is HttpServletResponseWrapper
). We do it this way to wrap a kerberized request, as follows
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;
}
}
这篇关于使用自定义身份验证筛选器时,使用getRemoteUser()访问用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!