springboot添加ssl实现https访问(http自动跳转)

2022/2/5 6:13:50

本文主要是介绍springboot添加ssl实现https访问(http自动跳转),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录
  • Step1
  • Step2
  • Step3
  • Step4
  • Step5

Step1

去搞一个证书,我的是腾讯买域名送的

Step2

下载jks格式的

Step3

放到项目的resource目录下的ssl文件夹下(需要new)

Step4

新建配置类,用于自动重定向到https

package club.shengcong.sendemail.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.beans.factory.annotation.Value;
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.context.annotation.Configuration;

/**
 * https配置类
 *
 * @author 金聖聰
 * @version v1.0
 * @email jinshengcong@163.com
 * @since Created in 2022/02/04 0:46
 */
@Configuration
public class HttpsConfiguration {
    @Value("${http-port}")
    private int port;

    @Value("${server.port}")
    private int sslPort;

    @Bean
    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(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(port);
        connector.setSecure(false);
        connector.setRedirectPort(sslPort);
        return connector;
    }
}

Step5

修改配置类

# https的端口
server.port=443
# SSL证书路径 一定要加上classpath:
server.ssl.key-store=classpath:ssl/XXX.jks
# SSL证书私钥
server.ssl.key-store-password=XXXX
# 证书类型
server.ssl.key-store-type=JKS
# http重定向https配置
http-port=80

# 项目路径
server.servlet.context-path=/XXX

Tips: 直接docker部署的时候端口号问题

需要同时开两个端口才能正常访问

-p 80:80 -p 443:443


这篇关于springboot添加ssl实现https访问(http自动跳转)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程