我获得了多个 IP,我必须仅通过 https 将其列入白名单。我已经通过自签名证书设置了 https 。代码是这样的:
@EnableWebSecurity
@Configuration
public class WebMvcSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().antMatchers("/secure/**").requiresSecure();
}
}
我需要将给定网址的 IP 列入白名单,例如 secure/dothis
、 secure/dothat
、secure/dothisalso
。如何做到这一点?
我使用的是 Spring Boot 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;
}
}
}
最佳答案
如果您使用http.authorizeRequests()
你可以用 hasIpAddress()
链接它将 IP 列入白名单以访问 antMatcher
中的给定模式。然后可以使用 and()
链接它强制使用安全通道。例如:
http.authorizeRequests()
.antMatchers("/secure/**").hasIpAddress("11.11.11.11").anyRequest().permitAll().and().requiresChannel().anyRequest().requiresSecure();
关于java - 通过 https 给定 IP 地址的 Spring Boot 白名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61905242/