Spring Boot中啓動HTTPS

Spring Boot中啓動HTTPS

如果你使用Spring Boot,並且想在內嵌tomcat中添加HTTPS,需要如下步驟

  • 要有一個證書,買的或者自己生成的

  • 在Spring Boot中啓動HTTPS

  • 將HTTP重定向到HTTPS(可選)

獲取SSL證書

有兩種方式

  • 自己通過keytool生成

  • 通過證書授權機構購買

這裏作爲演示,採用keytool生成

輸入下面的命令,根據提示輸入信息

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 code for this unit?
[Unknown]:
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
[no]: yes/是

會生成一個PKCS12格式的叫做keystore.p12的證書,之後啓動Spring Boot時會引用這個證書

Spring Boot 中開啓HTTPS

默認情況下Spring Boot內嵌的Tomcat服務器會在8080端口啓動HTTP服務,Spring Boot允許在application.properties中配置HTTP或HTTPS,但是不可同時配置,如果兩個都啓動,至少有一個要以編程的方式配置,Spring Boot官方文檔建議在application.properties中配置HTTPS,因爲HTTPS比HTTP更復雜一些,可以參考spring-boot-sample-tomcat-multi-connectors的實例

在application.properties中配置HTTPS


server.port: 8081
server.ssl.key-store: classpath:keystore.p12
server.ssl.key-store-password: dooioo888
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat


這就夠了

將HTTP請求重定向到HTTPS(可選)

讓我們的應用支持HTTP是個好想法,但是需要重定向到HTTPS,上面說了不能同時在application.properties中同時配置兩個connector,所以要以編程的方式配置HTTP connector,然後重定向到HTTPS connector

這需要在配置類中配置一個TomcatEmbeddedServletContainerFactory bean,代碼如下

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

搞定!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章