diff --git a/template/entrance/web/src/main/java/{{.packagePath}}/entrance/web/config/SSLConfig.java b/template/entrance/web/src/main/java/{{.packagePath}}/entrance/web/config/SSLConfig.java new file mode 100644 index 0000000..ce97ed4 --- /dev/null +++ b/template/entrance/web/src/main/java/{{.packagePath}}/entrance/web/config/SSLConfig.java @@ -0,0 +1,71 @@ +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; + } +} \ No newline at end of file