SpringBoot安装SSL证书

一、前言

        本文介绍的是在SpringBoot环境中安装SSL证书的过程,关于HTTP与HTTPS的区别,可以移步我的另外一篇文章【计算机网络】浅析HTTP与HTTPS的区别


二、下载证书

        这边以在阿里云上申请的证书为例,点击下载选项

出现以下选项

因为SpringBoot是内嵌Tomcat的,因此我们选择Tomcat

下载下来后,有这两个文件

第一个后缀为pfx的文件,是证书主体文件,包含了当初申请证书的域名、颁发厂商、有效期限、申请人等信息。

第二个后缀为txt的文件,里面是证书的密码,待会儿会用到。


三、代码配置

(1)将pfx文件复制到SpringBoot的resource目录中

(2)在application.yml中配置以下信息

server:
  port: 443
  ssl:
    key-store: classpath:***.pfx
    key-store-password: 证书密码
    key-store-type: PKCS12

(3)配置http向https的重定向,即使前端依然访问http,也会被定向到https

package com.yang.plm.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpToHttpsConfig {
    /**
     * http重定向到https
     * @return
     */
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(80);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(443);
        return connector;
    }
}

接下来,就可以使用https访问接口啦!