这些说明适用于JHipster所基于的所有Spring Boot应用程序。我已经在一个新生成的JHipster 2.7项目上对此进行了测试。
从头开始时,您需要完成以下步骤:
首先,您需要在项目目录中生成自签名证书,这可以keytool
通过使用Java提供的实用程序脚本来完成:
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
Enter keystore password:
Re-enter new password:
What is your first and last name?
[UnkNown]:
What is the name of your organizational unit?
[UnkNown]:
What is the name of your organization?
[UnkNown]:
What is the name of your City or Locality?
[UnkNown]:
What is the name of your State or Province?
[UnkNown]:
What is the two-letter country code for this unit?
[UnkNown]:
Is CN=UnkNown, OU=UnkNown, O=UnkNown, L=UnkNown, ST=UnkNown, C=UnkNown correct?
[no]: yes
我选择了密码,mypassword
因此这是我将在下一步中使用的密码。完成此操作后,您将keystore.p12
在当前目录中看到一个。
现在,您需要为Tomcat添加HTTPS连接器属性。您可以在其中找到属性(yml)文件,src/main/resources/
并且需要更新application.yml
(或仅用于开发时application- dev.yml
使用以下属性):
server:
ssl:
key-store: keystore.p12
key-store-password: mypassword
keyStoreType: PKCS12
keyAlias: tomcat
现在,您可以使用Maven(如果您为JHipster应用程序选择了Gradle,则可以使用Gradle)打包应用程序,mvn clean package
并使用 运行该应用程序。您现在可以在 上访问您的应用程序
为简单起见,我没有更改端口,但理想情况下,您也应该在属性文件中对其进行更改,但是由于它们已经在其中定义application- dev.yml
,application- prod.yml
因此我将其省略了,因此您必须在其中进行更改或将其删除然后放入一般application.yml
您只能通过启用一个协议application.properties
,因此当您像上面那样执行此操作时,仅HTTPS可以工作。如果您还希望HTTP也能工作,并重定向到HTTPS,则必须添加@Configuration
如下所示的类
@Bean
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;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
该回复基本上是我在同一主题上的博客文章的副本:http : //www.drissamri.be/blog/java/enable-https-in-spring- boot/