# spring-boot-ssl-demo **Repository Path**: centy/spring-boot-ssl-demo ## Basic Information - **Project Name**: spring-boot-ssl-demo - **Description**: 用于示例如何在Spring Boot项目中配置SSL访问 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2018-10-13 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Spring Boot项目配置HTTPS访问 *对于通过Jar包启动的Spring Boot项目,不能通过原来配置Tomcat的方式配置HTTPS了,那么可以通过什么方式配置呢?* ## Spring Boot项目 通过一个简单的Spring Boot项目进行示例,项目中只依赖了spring-boot-starter-web,实现了一个hello的restful接口。 ![image.png](https://upload-images.jianshu.io/upload_images/7584230-5f1a4dec6e6e85aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - 访问“http://localhost:8443/demo/hello”,返回如下: ![image.png](https://upload-images.jianshu.io/upload_images/7584230-18ee86db3ad3fbc9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## Keytool生成证书 Java项目一般使用JKS或者PKCS12格式的证书,可以使用Java自动的keytool命令行工具生成。这里使用“keytool -genkeypair”的方式直接生成密钥对,也可使用keytool的其它方式,具体可以百度keytool的用法。 - shell命令: ``` keytool -validity 365 -genkeypair -v -alias localhost -keyalg RSA -storetype JKS -keystore localhost.jks -dname "CN=localhost,OU=cent,O=cent,L=GuangZhou,ST=GuangDong,c=cn" -storepass 123456 -keypass 123456 ``` 命令中各项参数意义如下: **-validity <参数>** : 有效天数。 **-genkeypair**:指生成密钥对 **-v**:详细日志输出 **-alias**:别名,**需要记住,后面配置需使用。** **-keyalg**:密钥算法,使用genkeypair时默认为DSA。 **-storetype**:密钥库格式 **-keystore**:密钥库名称(即保存密钥的文件名称) **-dname**:唯一判别名。 **-storepass**:密钥库密码口令。 **-keypass**:密钥的秘密口令。 - 执行成功结果如下图: ![image.png](https://upload-images.jianshu.io/upload_images/7584230-db0db1918b214f30.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 修改配置 修改应用配置,增加相关SSL配置,配置如下: ``` spring: application: name: spring-boot-ssl-demo server: port: 8443 ssl: key-store: classpath:certificate/localhost.jks #jks证书路径 key-store-password: 123456 #证书的密钥 key-store-type: JKS #证书格式 key-alias: localhost #别名 ``` ## HTTPS访问 重启Spring Boot服务。 访问“http://localhost:8443/demo/hello”时,返回结果如下,证明SSL已经启用。 ![image.png](https://upload-images.jianshu.io/upload_images/7584230-b736166623166c79.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 访问“http://localhost:8443/demo/hello”,返回结果如下,大功告成! ![image.png](https://upload-images.jianshu.io/upload_images/7584230-0c408ff42afedebe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 示例代码 码云:[https://gitee.com/centy/spring-boot-ssl-demo.git](https://gitee.com/centy/spring-boot-ssl-demo.git) ## 尾巴 - 因为使用的不是证书认证机构颁发的正式证书,而是自签名的证书,所以访问时,浏览器会提示不安全。 ![image.png](https://upload-images.jianshu.io/upload_images/7584230-48bd4dab93617dbb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - 当你使用Spring Boot+Spring Cloud构建微服务集群时,一般只有Gateway(zuul)对外提供服务,那么就可以在Gateway(zuul)服务中配置HTTPS访问,从而提高服务的安全性。