Spring Boot:为嵌入式tomcat启用HTTPS



使用以下命令创建密钥库:
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

在application.properties文件中添加了以下设置:

server.ssl.key-store=keystore.p12
server.ssl.key-store-password=######
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
#server port config
server.port=8080
server.http.port=8081

编写以下代码:

public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
            @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(initiateHttpConnector());
        return tomcat;
    }

应用程序启动良好,没有任何错误。我可以在日志中看到以下消息:s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (https) 8081 (http)

但当我发送请求https://localhost:8081/hello时,响应从服务器发回,服务器日志上没有任何活动。不确定发生了什么。

嵌入式Tomcat的启动消息清楚地表明您的ssl/tls连接正在使用server.port:指定的端口上运行

Tomcat started on port(s): 8080 (https)

所以您只是使用了错误的端口/协议组合。https://localhost:8080应该起作用。

但通常情况下,你的浏览器应该通过一条消息来抱怨。出于好奇,你可以在打电话时查看浏览器中发生了什么https://www.google.com:80

最新更新