sslConfig

This commit is contained in:
oyo
2025-12-14 16:29:28 +08:00
parent fa9ea6a1bc
commit d2e47dfe15

View File

@@ -1,71 +0,0 @@
package {{ .package }}.entrance.web.config;
import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
@Configuration
public class SSLConfig {
@Bean
public ServletWebServerFactory servletContainer(Environment env) {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
// 禁用自动配置的SSL如果存在
tomcat.setRegisterDefaultServlet(false);
if (hasSslConfig(env)) {
tomcat.addAdditionalTomcatConnectors(createSslConnector(env));
}
return tomcat;
}
private boolean hasSslConfig(Environment env) {
return env.containsProperty("ssl_certificate")
&& env.containsProperty("ssl_certificate-private-key");
}
private Connector createSslConnector(Environment env) {
String certPath = env.getProperty("ssl_certificate");
String keyPath = env.getProperty("ssl_certificate-private-key");
String httpsPort = env.getProperty("server.https.port", "8443");
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(Integer.parseInt(httpsPort));
// 明确设置SSL配置
connector.setProperty("SSLEnabled", "true");
connector.setProperty("sslProtocol", "TLS");
connector.setProperty("clientAuth", "false");
connector.setProperty("sslEnabledProtocols", "TLSv1.2,TLSv1.3");
// 处理证书路径
connector.setProperty("certificateFile", extractFilePath(certPath));
connector.setProperty("certificateKeyFile", extractFilePath(keyPath));
return connector;
}
private String extractFilePath(String classpathResource) {
if (classpathResource == null) return null;
if (classpathResource.startsWith("classpath:")) {
String resource = classpathResource.substring("classpath:".length());
try {
return new ClassPathResource(resource).getFile().getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("Failed to locate SSL certificate file", e);
}
}
return classpathResource;
}
}