springboot https配置 keytool證書
阿新 • • 發佈:2018-12-10
大致分為三大步:1:生成證書 2:properties檔案配置 3:設定http自動跳轉https
第二步:把證書放在rescurces檔案下,並在properties檔案中配置ssl
#你生成的證書在專案中的位置 server.ssl.key-store=classpath:server.keystore #建立證書時的密碼 server.ssl.key-store-password=123456 #證書型別 server.ssl.key-store-type=JKS #你建立證書時取的別名 server.ssl.keyAlias=server_cert
第三步:http自動跳轉https,在啟動類中注入這個兩個bean
package com.example.demo; import com.example.demo.core.jpa.repository.BaseRepositoryImpl; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; @SpringBootApplication @EnableAutoConfiguration @EnableJpaRepositories(repositoryBaseClass = BaseRepositoryImpl.class) public class ShiroApplication { static Logger logger = LoggerFactory.getLogger(ShiroApplication.class); public static void main(String[] args) { SpringApplication.run(ShiroApplication.class, args); } @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL");//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(8081); connector.setSecure(false); connector.setRedirectPort(8443); return connector; } }
最後在瀏覽器中輸入localhost:8081會自動跳轉到https://localhost:8443