SpringBoot配置支援HTTPS
阿新 • • 發佈:2018-12-12
讓自己的網站支援HTTPS
獲取證書
用Java自帶的keytools工具生成證書
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
引數說明
1.-storetype 指定金鑰倉庫型別
2.-keyalg 生證書的演算法名稱,RSA是一種非對稱加密演算法
3.-keysize 證書大小
4.-keystore 生成的證書檔案的儲存路徑
5.-validity 證書的有效期
Spring Boot啟用https
修改application.properties或者修改application.yml檔案
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=111111
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias:tomcat
將HTTP請求轉到HTTPS請求
程式入口類新增Http轉換器
@Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint constraint = new SecurityConstraint(); constraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); 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(8080); connector.setSecure(false); //監聽到http的埠號後轉向到的https的埠號 connector.setRedirectPort(8443); return connector; }