首页 > 解决方案 > 通过 https 给定 IP 地址的 Spring Boot 白名单

问题描述

我获得了多个 IP,我必须仅通过 https 将其列入白名单。我已经通过自签名证书设置了 https。代码是这样的:

@EnableWebSecurity
@Configuration
public class WebMvcSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.requiresChannel().antMatchers("/secure/**").requiresSecure();


    }
}

我需要将 ip 列入给定 url 的白名单,如secure/dothis, secure/dothat, secure/dothisalso。这个怎么做 ?

我正在使用弹簧启动 1.5.x

这是我的 ssl 连接器:

@Configuration
public class TomcatCustomizer {

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addAdditionalTomcatConnectors(createSslConnector());
        return tomcat;
    }

    private Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        try {
            File keystore = getKeyStoreFile();
            //File truststore = keystore;
            connector.setScheme("https");
            connector.setSecure(true);
            connector.setPort(8443);
            protocol.setSSLEnabled(true);
            protocol.setKeystoreFile(keystore.getAbsolutePath());
            protocol.setKeystorePass("password");
            //protocol.setTruststoreFile(truststore.getAbsolutePath());
            //protocol.setTruststorePass("password");
            protocol.setKeyAlias("demo");
            return connector;
        } catch (IOException ex) {
            throw new IllegalStateException(
                    "cant access keystore: [" + "keystore" + "] or truststore: [" + "keystore" + "]", ex);
        }
    }

    private File getKeyStoreFile() throws IOException {
        ClassPathResource resource = new ClassPathResource("keystore.jks");
        try {
            return resource.getFile();
        } catch (Exception ex) {
            File temp = File.createTempFile("keystore", ".tmp");
            // FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(temp));
            return temp;
        }
    }

}

标签: javaspringspring-bootspring-mvcspring-security

解决方案


如果您使用 ,http.authorizeRequests()您可以将其链接hasIpAddress()到白名单 ip,以从您的antMatcher. 然后可以使用 链接and()来强制使用安全通道。例如:

 http.authorizeRequests()
        .antMatchers("/secure/**").hasIpAddress("11.11.11.11").anyRequest().permitAll().and().requiresChannel().anyRequest().requiresSecure();

推荐阅读