SpringBoot配置支持https
spring boot因為是使用內置的tomcat,所以只需要一些簡單的配置即可。
1.首先打開命令行工具,比如cmd,輸入以下命令
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
2.然后在你的根目錄下面會看到一個.p12的文件,如下圖所示:
3.將它移到你的spring boot項目中的resources目錄下
4.最后在application.properties中添加以下配置:
server.port=8888
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=123456(此處密碼為第一步中創建.p12文件時你輸入的口令)
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
5.最后啟動你的spring boot項目即可用https的方式訪問你的接口了。
用戶訪問http自動跳轉到https,支持post方法
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; @Configuration public class HttpConnectorConfig { // 在某配置類中添加如下內容 // 監聽的http請求的端口,需要在application配置中添加http.port=端口號 如80 @Value("${http.port}") Integer httpPort; //正常啟用的https端口 如443 @Value("${server.port}") Integer httpsPort; // springboot2 寫法 @Bean public TomcatServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint constraint = new SecurityConstraint(); constraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addMethod("post"); //添加post方法 collection.addPattern("/*"); constraint.addCollection(collection); context.addConstraint(constraint); } }; 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(httpPort); connector.setSecure(false); //監聽到http的端口號后轉向到的https的端口號 connector.setRedirectPort(httpsPort); return connector; } }
---------------------
作者:顏藝學長
來源:CSDN
原文:https://blog.csdn.net/hwangfantasy/article/details/78403570
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
