在Tomcat中从HttpServletRequest.getRemoteUser()获取值而不修改应用程序 [英] Getting a value from HttpServletRequest.getRemoteUser() in Tomcat without modifying application
问题描述
(使用Java 6和Tomcat 6。)
(Using Java 6 and Tomcat 6.)
我有办法获得 HttpServletRequest.getRemoteUser()
在我的开发环境(即localhost)中返回一个值,而不需要修改我的应用程序的web.xml文件?
Is there a way for me to get HttpServletRequest.getRemoteUser()
to return a value in my development environment (i.e. localhost) without needing to modify my application's web.xml file?
我问的原因是验证实现当应用程序部署到远程环境时,由Web服务器和插件工具处理。在本地运行我显然没有插件工具或单独的Web服务器;我只是拥有Tomcat 6.我试图避免在我的应用程序中添加代码只是为了支持我的本地主机上的开发。
The reason I ask is that the authentication implementation when the app is deployed to a remote environment is handled by a web server and plugged-in tool. Running locally I obviously do not have the plugged-in tool or a separate web server; I just have Tomcat 6. I am trying to avoid adding code to my application merely to support development on my localhost.
我希望我可以修改context.xml或server.xml文件,它们将允许我设置远程用户ID或尝试从HTTP标头中提取它。
I am hoping there is a modification I can make to the context.xml or server.xml files that will let me set the remote user ID or that will try to pull it from a HTTP header or something.
推荐答案
这是一个概念验证 Valve
实现它:
Here is a proof of concept Valve
implementation which does it:
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.valves.ValveBase;
public class RemoteUserValve extends ValveBase {
public RemoteUserValve() {
}
@Override
public void invoke(final Request request, final Response response)
throws IOException, ServletException {
final String username = "myUser";
final String credentials = "credentials";
final List<String> roles = new ArrayList<String>();
// Tomcat 7 version
final Principal principal = new GenericPrincipal(username,
credentials, roles);
// Tomcat 6 version:
// final Principal principal = new GenericPrincipal(null,
// username, credentials, roles);
request.setUserPrincipal(principal);
getNext().invoke(request, response);
}
}
(使用Tomcat 7.0.21测试) 。)
(Tested with Tomcat 7.0.21.)
编译它,将它放在一个jar中并将jar复制到 apache-tomcat-7.0.21 / lib
文件夹。您需要修改 server.xml
:
Compile it, put it inside a jar and copy the jar to the apache-tomcat-7.0.21/lib
folder. You need to modify the server.xml
:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="remoteuservalve.RemoteUserValve" />
...
我认为它适用于引擎
和上下文
容器。
I suppose it works inside the Engine
and Context
containers too.
更多信息:
- The Valve Component
- Valve javadoc
这篇关于在Tomcat中从HttpServletRequest.getRemoteUser()获取值而不修改应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!