Spring Boot2中配置HTTPS

1.生成证书

使用jdk,jre中的keytool.exe生成自签名的证书,需要配置JAVA_HOME和path环境变量,即jdk的环境变量。命令如下:

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

然后可以找到C:/用户/用户名/keystore.p12,复制到springboot项目根目录

2.加入页面和映射

添加一个index.html页面在resources/stastic下面
并添加一个配置类MVCConfig 
@Configuration
public class MVCConfig implements WebMvcConfigurer {
    public void addViewControllers(ViewControllerRegistry registry)         {
        registry.addViewController("/").setViewName("/index");
        registry.addViewController("/index").setViewName("/index");
    }  
}

3.springboot 配置SSL

在application.properties中配置

server.port=8080
#SSL https证书配置
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=123456
#行业标准PKCS12
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=tomcat

现在就可以访问https://localhost:8080/index了

4.http转向https

在MVCConfig加入如下代码

/*配置http自动转为https*/
    @Bean
    public ServletWebServerFactory servletWebServerFactory(){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");//机密的
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern("/*");
                securityConstraint.addCollection(securityCollection);
                context.addConstraint(securityConstraint);
            }
        };
        factory.addAdditionalTomcatConnectors(httpConnector());
        return factory;
    }

    @Bean
    public Connector httpConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8888);
        connector.setSecure(false);
        connector.setRedirectPort(8080);
        return  connector;
    }

记住在springboot2以上,没有了TomcatEmbeddedServletContainerFactory,变成了TomcatServletWebServerFactory

然后访问http://localhost:8888/index会转向https://localhost:8080/index

猜你喜欢

转载自www.cnblogs.com/sufferingStriver/p/9026902.html