将 HTTP 转换成 HTTPS 需要证书。证书可以通过自己生成或者从 CA 厂商购买获得。
    JDK 有 keytool 工具,可以生成证书:

    1. $ keytool -genkeypair -alias osiiap_web_api -keyalg RSA -keysize 2048 -storetype PKCS12 -validity 3650 -keypass password -storepass password -keystore web-api.p12
    • -alias 证书的别名
    • -keyalg -keysize 证书使用的算法和证书长度
    • -storetype 存储的类型
    • -validity 证书的有效期限
    • -keypass -storepass 证书的密码和存储的密码

    接着就可以在 application.yml 文件中写上对应信息即可。

    1. server:
    2. # port 为非必须
    3. port: 443
    4. ssl:
    5. key-alias: osiiap_web_api
    6. key-store: web-api.p12
    7. key-store-password: password

    现在就可以使用 https 来访问该程序。但是我们想将 http 永久重定向到 https,用到的技术就是将 80 端口转到 443。
    可以创建 Spring Boot 的配置类来实现:

    1. @SpringBootConfiguration // 注意这里必须是 @SpringBootConfiguration 注解。才会认定为这是一个 Spring Boot 的注解。
    2. public class HttpsConfig {
    3. @Bean
    4. TomcatServletWebServerFactory tomcatServletWebServerFactory() {
    5. TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
    6. @Override
    7. protected void postProcessContext(Context context) {
    8. SecurityConstraint constraint = new SecurityConstraint();
    9. constraint.setUserConstraint("CONFIDENTIAL");
    10. SecurityCollection collection = new SecurityCollection();
    11. collection.addPattern("/*");
    12. constraint.addCollection(collection);
    13. context.addConstraint(constraint);
    14. }
    15. };
    16. factory.addAdditionalTomcatConnectors(createTomcatConnector());
    17. return factory;
    18. }
    19. private Connector createTomcatConnector() {
    20. Connector connector = new
    21. Connector("org.apache.coyote.http11.Http11NioProtocol");
    22. connector.setScheme("http");
    23. connector.setPort(80);
    24. connector.setSecure(false);
    25. connector.setRedirectPort(443);
    26. return connector;
    27. }
    28. }