SpringBoot2.0项目配置https访问

要使用https首先我们需要有证书,由于我们自己生成的证书会被多数浏览器不信任,所以我们采用申请的免费证书来演示。

一、先来说一说如何申请证书吧

1.登录腾讯云,选择云产品——>SSL证书管理

2.点击申请证书,选择亚洲诚信,按要求填写完信息,提交后大约十分钟,证书会发到你的邮箱

二、现在我们来为项目配置https

1.下载你所需要类型的证书,并将其放入项目resources目录下

Windows IIS下的数字证书格式一般为.pfx
Java tomcat 下的数字证书格式一般为.jks或.store
Apache和nginx一般是.pem

2.打开application.properties配置文件,添加如下配置

#端口号
server.port=443
#你生成的证书名字
server.ssl.key-store=classpath:放在resources下证书的名字
#密钥库密码
server.ssl.key-store-password=申请证书时添加的秘钥库口令
server.ssl.keyStoreType=JKS

这样我们的https就配置好了,将项目放到申请证书时填入的域名解析到的服务器上进行测试

三、当用户访问http端口的时候,我们需要重定向到https

在启动类中添加如下两个方法,更改tomcat配置

@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(initiateHttpConnector());
        return tomcat;
    }

    /**
     * 让我们的应用支持HTTP是个好想法,但是需要重定向到HTTPS,
     * 但是不能同时在application.properties中同时配置两个connector,
     * 所以要以编程的方式配置HTTP connector,然后重定向到HTTPS connector
     * @return Connector
     */
    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(80); // http端口
        connector.setSecure(false);
        connector.setRedirectPort(443); // application.properties中配置的https端口
        return connector;
    }

猜你喜欢

转载自blog.csdn.net/qq_40715775/article/details/82780881