SSL(Secure Sockets Layer 安全套接層),及其繼任者傳輸層安全(Transport Layer Security,TLS)是爲網絡通訊提供安全及數據完整性的一種安全協議。TLS與SSL在傳輸層對網絡鏈接進行加密。html
在B/SWeb的應用中,是經過Https實現SSL的,Https是http的安全版,Https的安全基礎就是SSLjava
在Spring Boot中 tomcat是內置的,因此和SpringMvc實現Https(將證書配置到tomcat/conf/server.xml)的方式不一樣。web
下面介紹如何在Spring Boot中實現Https spring
1:利用java JDK 自帶工具 keytool 建立證書,建立證書這部分略過,可自行百度。apache
2:springboot配置SSLtomcat
添加一個index.html放入到src/main/resources/static下,做爲測試安全
將keytool生成的.keystore文件複製到項目的根路徑,而後在application.properties中作以下配置:springboot
server.port=8443 server.ssl.key-store=.keystore #建立證書時輸入的密碼 server.ssl.key-store-password=11111 server.ssl.keyStoreType=JKS server.ssl.keyAlias=tomcat
此時啓動項目,訪問:https:localhost:8443 就能夠看到index.html了網絡
3 http跳轉到httpsapp
不少時候咱們輸入http訪問網站時例如百度,都會自動跳轉到https上,要實現這個功能 咱們須要配置EmbeddedServletContainerFactory
package com.wisely.ch7_4; import java.util.concurrent.TimeUnit; 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.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.ErrorPage; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; @SpringBootApplication public class Chapter511Application { public static void main(String[] args) { SpringApplication.run(Ch74Application.class, args); } @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @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.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; } }
此時啓動項目,訪問8080端口 會自動跳轉到https 8443