最近一直在搞微信小程序,然後我是負責後端接口的設計,功能的實現。
因爲小程序中請求接口需要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包啦