Spring Boot配置SSL實現https請求
阿新 • • 發佈:2020-12-01
Spring Boot配置SSL實現https請求
1. 生成SSL證書
- 專業的SSL證書較為昂貴,可以在騰訊雲或者阿里雲上申請免費的SSL證書。
- 如果只是做簡單的demo,可以使用java自帶的keytool工具生成SSL證書。
2. 使用keytool工具生成SSL證書
以windows系統為例(如果是linux系統,將keytool.exe替換為keytool即可),在終端輸入
keytool.exe -genkey -alias test -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore test.p12 -validity 3650
引數解釋
-genkey: 生成SSL證書 -alias: 證書別名 -storetype: 祕鑰倉庫型別 -keyalg: 生成證書演算法 -keysize: 證書大小 -keystore: 生成證書儲存路徑 -validity: 證書有效期
注意在終端輸入生成SSL命令後,“您的名字和姓氏是什麼?”這一項需要設定為你的域名,本地測試的話便是localhost,其餘選項可以忽略。
3. Spring Boot專案配置SSL
在配置檔案application.yml中新增如下內容
server: # 配置埠號,https預設埠號為443,如果443埠被佔用,將佔用443埠的程序殺死 port: 443 # 配置ssl證書 ssl: # SSL證書test.p12與application.yml放在同級目錄下 key-store: classpath:test.p12 key-store-password: 123456 keyStoreType: PKCS12 keyAlias: test
4. 測試SSL是否配置成功
建立HelloController
@RestController @CrossOrigin(origins = "*") public class HelloController { @GetMapping(value = "/hello") public String sayHello() { return "Hello World!"; } }
使用瀏覽器訪問https://localhost/hello ,看是否正確響應
(第一次訪問時,瀏覽器會警告,這是因為自己生成的SSL證書不被瀏覽器認可)。
如果出錯:檢查application.yml中埠號是否為443,檢查443埠是否被其他程序佔用。
5. http請求自動轉換為https請求
修改入口類HttpsApplication,此配置方式需要SpringBoot2.0以上
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.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; @SpringBootApplication public class HttpsApplication { public static void main(String[] args) { SpringApplication.run(HttpsApplication.class, args); } @Bean public Connector connector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); // 捕獲http請求,並將其重定向到443埠 connector.setScheme("http"); connector.setPort(80); connector.setSecure(false); connector.setRedirectPort(443); return connector; } @Bean public TomcatServletWebServerFactory servletContainer() { // 對http請求新增安全性約束,將其轉換為https請求 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(connector()); return tomcat; } }