2011-10-03 104 views
8

我配置了tomcat進行基本身份驗證。 我不希望任何人訪問我的Web應用程序,但該應用程序正在提供Web服務。 所以我想從基本身份驗證繞過特定的IP地址(即IP不應該要求身份驗證。)Tomcat:繞過指定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> 

謝謝, Chetan。

回答

9

如果你想只允許幾個IP地址,並且不允許其他人,那麼你需要的是Remote Address Filter Valve

如果您希望來自未知IP地址的客戶端看到基本登錄對話框並且可以登錄,您需要自定義Valve。在RemoteAddrValve(和它的父RequestFilterValve類的來源是一個很好的起點。看看my former answer too

不管怎樣,下面是的概念代碼證明。它把一個充滿PrincipalRequest如果客戶是來自一個值得信賴的IP,因此登錄模塊將不要求輸入密碼,否則它不觸及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" /> 
+0

謝謝palacsinit,我會嘗試添加此功能,並且會盡快發佈結果。 – Chetan

+1

它工作完美,非常感謝palacsint。 – Chetan