SpringBoot2 webflux中使用HTTPS(SSL)示例

说明

由于SpringBoot2新版本的发布,有些新特性,在此就不一一列举。由于这些变化,在实际开发中带来了一些问题,在此记录下,避免其他人再掉坑。主要步骤包括:

  • 生成证书
  • 修改配置文件
  • 增加配置类
  • 实现HTTP转HTTPS

生成证书

  1. 获取证书可通过购买,或者本机生成,以下演示本机生成
  2. 通过keytool -genkey alias selfsigned_sslserver生成的.keystore已经过时了,不推荐
  3. 在正确配置完JDK环境变量的前提下,在任意目录,执行命令
    keytool -genkey -alias selfsigned_sslserver-storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
  4. 按提示填好相关信息……
  5. 在当前目录下会生成一个keystore.p12文件,即证书文件

修改配置文件

  1. 将证书文件放入resources目录下
  2. 修改application.properties文件
server.port=443
server.ssl.key-alias=selfsigned_sslserver
server.ssl.key-store-password=your_passwd
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-type=PKCS12   

增加配置类,包括实现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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class SSLConfig {

     @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(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}

猜你喜欢

转载自blog.csdn.net/u013870094/article/details/81413765