在Tomcat中从HttpServletRequest.getRemoteUser()获取值而不修改应用程序

Mar*_*ark 7 java tomcat basic-authentication

(使用Java 6和Tomcat 6.)

有没有办法让我HttpServletRequest.getRemoteUser()在我的开发环境(即localhost)中返回一个值,而无需修改我的应用程序的web.xml文件?

我问的原因是,当应用程序部署到远程环境时,身份验证实现由Web服务器和插件工具处理.在本地运行我显然没有插件工具或单独的Web服务器; 我只是有Tomcat 6.我试图避免在我的应用程序中添加代码仅仅是为了支持我的localhost上的开发.

我希望我可以对context.xml或server.xml文件进行修改,这些修改将允许我设置远程用户ID或尝试从HTTP标头或其他内容中提取它.

pal*_*int 7

以下是概念Valve实现的证明:

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

}
Run Code Online (Sandbox Code Playgroud)

(使用Tomcat 7.0.21测试.)

编译它,将它放在一个jar中并将jar复制到该apache-tomcat-7.0.21/lib文件夹中.你需要修改server.xml:

<Host name="localhost"  appBase="webapps"
    unpackWARs="true" autoDeploy="true">

    <Valve className="remoteuservalve.RemoteUserValve" />
...
Run Code Online (Sandbox Code Playgroud)

我想它的工作原理内部EngineContext容器了.

更多信息: