这些说明适用于JHipster所基于的所有Spring Boot应用程序。我已经在一个新生成的JHipster
2.7项目上对此进行了测试。
从头开始时,您需要完成以下步骤:
- 生成自签名证书
- 如Spring Boot文档中所述将SSL属性添加到application.properties或application.yml
- (可选)将HTTP重定向到HTTPS
生成自签名证书
首先,您需要在项目目录中生成自签名证书,这可以
keytool通过使用Java提供的实用程序脚本来完成:
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650Enter 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 pre for this unit? [Unknown]: Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct? [no]: yes
我选择了密码,
mypassword因此这是我将在下一步中使用的密码。完成此操作后,您将
keystore.p12在当前目录中看到一个。
将SSL属性添加到您的application.properties
或[SpringBoot文档中](http://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-configure-
ssl)
application.yml提到的
现在,您需要为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 cleanpackage并使用 mvn spring-boot:run 运行该应用程序。您现在可以在 https://
localhost:8080 上访问您的应用程序
为简单起见,我没有更改端口,但理想情况下,您也应该在属性文件中对其进行更改,但是由于它们已经在其中定义
application-dev.yml,
application-prod.yml因此我将其省略了,因此您必须在其中进行更改或将其删除然后放入一般
application.yml
(可选)将重定向HTTP添加到HTTPS
您只能通过启用一个协议
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/



