如何在Spring Boot 2中配置https?

时间:2018-06-27 22:57:25

标签: spring-boot spring-security

我已经使用keytool生成了自签名证书。我已添加到资源文件夹。 在我的application.properties中,添加了

security.require-ssl=true

# The format used for the keystore 
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password=
# The alias mapped to the certificate
server.ssl.key-alias=tomcat

我的配置文件:

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

但是我仍然无法使用https访问我的应用程序吗?

1 个答案:

答案 0 :(得分:3)

EmbeddedServletContainerFactory中没有Spring boot 2,请使用TomcatServletWebServerFactory

@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(getHttpConnector());
    return tomcat;
}