美文网首页
Spring Boot自定义Tomcat添加黑白名单

Spring Boot自定义Tomcat添加黑白名单

作者: 站在海边看远方 | 来源:发表于2020-10-19 19:30 被阅读0次

tomcat添加黑白名单限制IP访问,可以在server.xml里添加配置

白名单设置allow即可

<Context path="" docBase="" debug="0" reloadable="true" >
                <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="192.168.1.2|192.168.2.3" deny=""/>    --只允许192.168.1.2和192.168.2.3
</Context>

黑名单设置deny即可

<Context path="" docBase="xxxAdmin" debug="0" reloadable="true" >
                <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="" deny="192.168.1.2|192.168.2.3"/>    --拒绝192.168.1.2和192.168.2.3 
</Context>

deny的优先级比allow要高。

Spring Boot内嵌的tomcat是一个应用一个context,无法在xml文件里配置。

如果想启用黑白名单,就需要自定义tomcat,设置context

@Configuration
public class TomcatConfig {

    @Bean
    public EmbeddedServletContainerFactory servletContainer(){
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        
        //black and white list of IP
        String allow = "127.0.0.1|10.45.99.23|10.45.80.45";
        String deny = "172.16.17.10|172.16.17.20|172.16.17.33";

        RemoteAddrValve remoteAddrValve = new RemoteAddrValve();
        remoteAddrValve.setAllow(allow);
        remoteAddrValve.setDeny(deny);

        tomcat.addContextValves(remoteAddrValve);
       
        return tomcat;
    }
}

获得容器后可以直接设置context,为context添加Value即可。

相关文章

网友评论

      本文标题:Spring Boot自定义Tomcat添加黑白名单

      本文链接:https://www.haomeiwen.com/subject/wtdlmktx.html