微信小程序—Java后端提供Https服务以及踩过的坑
文章目录
前言
公司小程序开发阶段完成后,小程序需要发布测试版本,需要在公网环境的服务。注:微信小程序服务必须使用Https域名,否则认证不通过,页面也会一直抛网络不可用。
提示:以下是本篇文章正文内容,下面案例可供参考
一、自签名证书
1、KeyTool工具生成证书
keytool -genkeypair -alias tomcat_https -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore /application/ssh/tomcat_https.keystore -storepass 123456 -storetype PKCS12
2、添加配置文件
将生成的证书放入到项目配置文件中,和yml配置文件放一起
3、更改yml配置
server:
port: 8070
ssl:
key-password: 123456
key-store-password: 123456
key-store-type: PKCS12
key-store: classpath:tomcat_https.keystore
key-alias: tomcat_https
4、测试
重启项目后,进入Swagger地址,提示:不是安全的连接,但是不存在,直接在高级中继续访问,成功出现页面了。
很高兴的让前端修改配置文件,重新发布测试版,等待正常访问,结果。。。。。。
无奈之下,只好去腾讯云申请SSL证书。
二、SSL证书
1.腾讯云申请免费SSL证书
申请成功后,将证书下载下来并解压,会看到以下目录,我们是后端服务,选择Tomcat文件内文件放入后端项目配置文件即可。
2.修改配置文件
server:
port: 443
http-port: 80
ssl:
key-password: 123456
key-store-password: 123456
key-store-type: JKS
key-store: config/xxx.xxx.com.jks
重启服务后,再次访问Swagger地址,不会出现上面提示的:您的连接不是私密连接,意味着大功告成。
3.http强制转换为Https
package com.study.cti.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* http强制跳转https
*/
@Configuration
public class HttpsConfig {
@Value("${server.port}")
private int sslPort;//https的端口
@Value("${server.http-port}")
private int httpPort;//http的端口
@Bean
public TomcatServletWebServerFactory servletContainerFactory() {
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);
}
};
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//设置将分配给通过此连接器接收到的请求的方案
connector.setScheme("http");
//true: http使用http, https使用https;
//false: http重定向到https;
connector.setSecure(false);
//设置监听请求的端口号,这个端口不能其他已经在使用的端口重复,否则会报错
connector.setPort(httpPort);
//重定向端口号(非SSL到SSL)
connector.setRedirectPort(sslPort);
tomcat.addAdditionalTomcatConnectors(connector);
return tomcat;
}
}
感谢以下作者提供参考: