application.yml生成数字证书:
keytool -genkey -dname "CN=XFDServer,OU=XFDUnit,O=XFD,L=TaiYuan, ST=ShanXi, C=CN" -keysize 2048 -alias server -keyalg RSA -keystore d:/server.jks -keypass 123456 -storepass 123456 -validity 36500
工程配置:
server:
port: 9443
http:
port: 9080
ssl:
enabled: true
key-store: d:/server.jks
key-store-type: JKS
key-store-provider: SUN
key-alias: server
key-store-password: 123456
代码片段:
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TomcatServerConfig {
@Value("${server.http.port}")
private Integer httpPort;
@Value("${server.port}")
private Integer httpsPort;
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(connector());
return tomcat;
}
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(httpPort);
connector.setSecure(false);
// Redirect到端口
connector.setRedirectPort(httpsPort);
return connector;
}
}