玖叶教程网

前端编程开发入门

Java,SpringBoot,内置(嵌入式)Tomcat配置成HTTPS服务

生成数字证书:

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

其他参考:命令生成代码生成

工程配置:

application.yml

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;
    }

}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言