微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

如果您只想允许几个IP地址,而不允许其他人使用,则您需要Remote Address Filter Valve

如果希望来自未知IP地址的客户端看到基本的登录对话框,并且可以自定义登录,则可以登录Valve。在源RemoteAddrValve(和它的父类RequestFilterValve是出发点良好的。看看我以前的答案太

无论如何,下面是概念证明代码。如果客户端来自受信任的IPPrincipalRequest则会填入,因此登录模块将不会要求输入密码。否则它不会碰到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" />

解决方法

我已经配置了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>

谢谢,谢坦。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。