1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tomcat basic認証で特定のIPアドレスをバイパスする

Last updated at Posted at 2017-04-30

TomcatでBasic認証してさせているとき、特定のIPアドレスだけバイパスする方法が
下記に記載されてました。
http://stackoverflow.com/questions/7631974/tomcat-bypass-basic-authentication-for-specified-ip-address

ただ、この方法では1つのIPしか対応してないので、下記のように少し変更して複数のIPに対応できるようにしました。

AutoLoginValve.java
package remoteuservalve; 
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

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();
		String[] trustedIpAddressArray=trustedIpAddress.split(",");
		List<String> trustedIpAddressList = Arrays.asList(trustedIpAddressArray);
        final boolean isTrustedIp = trustedIpAddressList.contains(remoteAddr);
        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) {
        this.trustedIpAddress = trustedIpAddress;
    }
}

server.xmlでは下記のようにカンマ区切りします。

text:server.xml
<Valve className="remoteuservalve.AutoLoginValve" trustedIpAddress="192.168.1.10,192.168.1.11" />
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?