Tomcat:绕过指定IP地址的基本身份验证

时间:2011-10-03 07:08:49

标签: tomcat

我已经为tomcat配置了基本身份验证。 我不希望任何人访问我的Web应用程序,但该应用程序正在提供Web服务。 所以我想从基本身份验证中绕过一个特定的IP地址。(该ip不应该要求身份验证。)

tomcat-users.xml:

<tomcat-users>
<user username="user" password="password" roles="user"/>
</tomcat-users>

web.xml:

<security-constraint>
<web-resource-collection>
  <web-resource-name>Entire Application</web-resource-name>
  <url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
  <role-name>user</role-name>
</auth-constraint>
</security-constraint>


<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>You must enter your login credentials to continue</realm-name>
</login-config>

<security-role>
   <description>
      The role that is required to log in to the Application
   </description>
   <role-name>user</role-name>
</security-role>

谢谢, 阿赫亚。

1 个答案:

答案 0 :(得分:9)

如果您只想允许几个IP地址并且不允许其他人,Remote Address Filter Valve就是您所需要的。

如果您希望来自未知IP地址的客户端看到基本登录对话框并且可以登录,则需要自定义ValveRemoteAddrValve(以及它的父类RequestFilterValve的来源是一个很好的起点。看看my former answer too

无论如何,下面是概念证明代码。如果客户端来自可信IP,则它会将Principal填充到Request,以便登录模块不会要求输入密码。否则它不会触及Request对象,用户可以照常登录。

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 AutoLoginValve extends ValveBase {

    private String trustedIpAddress;

    public AutoLoginValve() {
    }

    @Override
    public void invoke(final Request request, final Response response) 
             throws IOException, ServletException {
        final String remoteAddr = request.getRemoteAddr();
        final boolean isTrustedIp = remoteAddr.equals(trustedIpAddress);
        System.out.println("remoteAddr: " + remoteAddr + ", trusted ip: " 
                + trustedIpAddress + ", isTrustedIp: " + isTrustedIp);
        if (isTrustedIp) {
            final String username = "myTrusedUser";
            final String credentials = "credentials";
            final List<String> roles = new ArrayList<String>();
            roles.add("user");
            roles.add("admin");

            final Principal principal = new GenericPrincipal(username, 
                credentials, roles);
            request.setUserPrincipal(principal);
        }

        getNext().invoke(request, response);
    }

    public void setTrustedIpAddress(final String trustedIpAddress) {
        System.out.println("setTrusedIpAddress " + trustedIpAddress);
        this.trustedIpAddress = trustedIpAddress;
    }

}

server.xml的配置示例:

<Valve className="autologinvalve.AutoLoginValve" 
    trustedIpAddress="127.0.0.1" />