Getting a value from HttpServletRequest.getRemoteUser() in Tomcat without modifying application

后端 未结 2 1247
孤独总比滥情好
孤独总比滥情好 2020-12-14 13:12

(Using Java 6 and Tomcat 6.)

Is there a way for me to get HttpServletRequest.getRemoteUser() to return a value in my development environment (i.e. local

相关标签:
2条回答
  • 2020-12-14 13:17

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

    (Tested with Tomcat 7.0.21.)

    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.

    More information:

    • The Valve Component
    • Valve javadoc
    0 讨论(0)
  • 2020-12-14 13:39

    Use a local, file-based realm for testing. Check your conf/tomcat-users.xml and create roles and users for your application and enable the security constraints in your web.xml. There are good examples in the tomcat-users.xml.

    0 讨论(0)
提交回复
热议问题