Spring Boot 配置 SSL 证书(开启 https)

642人浏览 / 0人评论

参考

http://tools.jbritian.com/link/k

1、下载证书

压缩包里有证书文件和密码(如果申请证书的时候自己设置了密码,就要用自己设置的密码)。

 

2、Spring Boot配置证书

在 Spring Boot 配置文件 application.yml 中添加以下的配置(建议证书文件放在项目文件夹 /src/main/resources 下):

server:
  port: 443
  ssl:
    enabled: true
    key-store: classpath:tools.jbritian.com.jks
    key-store-password: 证书密码
    key-store-type: JKS

3、配置 http 自动跳转 https

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.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @Author FengHao
 * @Date 2023/3/11
 * @Description:
 **/
@Component
public class HttpConfig {

    /**
     * http自动跳转https
     * 只有当配置文件中 server.ssl.enabled 的值为 true 时才会跳转
     */
    @Bean
    @ConditionalOnProperty(name = {"server.ssl.enabled"}, havingValue = "true")
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @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(redirectConnector());
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(80); // http端口
        connector.setSecure(false);
        connector.setRedirectPort(443); // 跳转的https端口,就是配置文件中的项目端口
        return connector;
    }

}

全部评论