「Spring Boot笔记」在Spring Boot项目中启用HTTPS

193 阅读1分钟

申请SSL证书

我在阿里云上买了一个域名www.wangsy1217.xyz,并且已经备过案了。阿里云上可以申请免费的SSL证书,所以我就申请了阿里云的SSL证书。大体的操作流程是:进入SSL证书菜单 --> 点击立即购买 --> 点击创建证书 -->点击下载按钮下载相关证书。我们下载的是JKS证书。

阿里云SSL证书.png

配置SSL证书

将证书文件复制到Spring Boot项目中的src/main/resources目录下,然后在application.properties文件中配置如下内容:

# 证书文件位置
server.ssl.key-store=classpath:证书文件名.jks
# 签名密码
server.ssl.key-store-password=签名密码
# 密钥仓库类型
server.ssl.keyStoreType=JKS

本地域名配置

修改C:\Windows\System32\drivers\etc文件夹下的hosts文件,添加如下内容:

127.0.0.1 www.wangsy1217.xyz
::1 www.wangsy1217.xyz

验证

启动项目,在浏览器地址栏中输入https://www.wangsy1217.xyz:9030/health-inn/weixin/auth看是否能正常访问并返回正确的结果。

自动转发http请求


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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatConfig {

    /**
     * https请求端口号
     */
    @Value("${server.port}")
    private int redirectPort;
    /**
     * http请求端口号
     */
    @Value("${http.port}")
    private int httpPort;

    @Bean
    TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory factory = 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);
            }
        };
        factory.addAdditionalTomcatConnectors(createTomcatConnector());
        return factory;
    }

    private Connector createTomcatConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(httpPort);
        connector.setSecure(false);
        connector.setRedirectPort(redirectPort);
        return connector;
    }
}

配置完成后,重新启动项目,在浏览器地址栏中输入http://www.wangsy1217.xyz:8030/health-inn/weixin/auth会自动重定向到https://www.wangsy1217.xyz:9030/health-inn/weixin/auth

注:Spring Boot内置的Web服务器启动时的端口号是9030,即https的端口号是9030,我们配置的http的端口号是8030,需要区分下这两个端口号。

参考资料