最近一直在搞微信小程序,然后我是负责后端接口的设计,功能的实现。
因为小程序中请求接口需要https格式。
第一次研究这个,搞了今天一天,虽然走了很多弯路! 不过! 现在发现! 很简单的!
大概介绍
下载SSL证书,因为我用的是阿里云服务器,所以就直接从阿里云申请了免费的证书
将证书复制到项目中并进行配置
一:SSL证书
因为我是用了springboot内置的tomcat,所以下载的就是tomcat版本的证书;
一个pfx文件,一个pfx密码文件
二:项目配置
打开项目目录,在src->main->resources中,把我们上面的两个文件放进去
接下来就是修改application配置文件,application配置文件有两种格式properties和yml ;
内容都相同,但就是格式不同;并且千万不要混用!
我项目文件使用的yml,我将properties的也写在下面。
application.yml添加的内容如下:
server:
port: 443 #https的默认端口就是433 不能修改
ssl:
key-store: classpath:3516608_www.shiwanfute.cn.pfx #证书pfx的名字
key-store-type: PKCS12 #证书的类型
key-store-password: ******** #pfx-password.txt中的密码
application.properties添加的内容如下:
三:如果也要使用http,可以加入以下代码,将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.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* http重定向到https
* @return
*/
@Configuration
public class SecurityConfig
{
@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(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(8080);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
}
四:将项目打包成jar包
打开项目文件夹-->targer文件夹,就可以看到jar包啦