在文章【HTTPS配置】中,介绍了怎么样通过JDK中的Keytool工具来生成一个数字证书,证书生成后,怎么样在Java项目中使用呢?本文将介绍如何在SpringBoot项目中使用生成的数字证书进行HTTPS安全配置。
1、通过JDK的keytool工具生成数字证书(详细说明参考HTTPS配置),指令如下:
keytool -genkey -alias projectHttps -keyalg RSA -keySize 2048 -keystore project.cer -validity 365
解释:此处的projectHttps和project.cer以及在创建过程中输入的password,将在SpringBoot项目中用到。
2、创建一个SpringBoot项目,在src/main/resources路径下创建application.properties文件,并配置如下内容:
server.port=9001
server.ssl.key-store=xxx
server.ssl.key-alias=xxx
server.ssl.key-store-password=xxx
解释:
server.ssl.key-store:步骤一中的project.cer
server.ssl.key-alias:步骤一中的projectHttps
server.ssl.key-store-password:步骤一中的创建时在控制台输入的password
3、创建接口请求并通过浏览器进行请求。
当请求方式为http时,结果如下:
修改请求方式为https时,结果如下:
注意:因为证书时自己生成的,不被浏览器认可,所以在使用https请求时,浏览器会提示:您的连接不是私密连接,此时只要添加信任或继续前进都可以。
4、在步骤3中通过http方式请求时报错,是因为SpringBoot不支持同时在配置中启动HTTPS和HTTP,这种情况下如果希望使用HTTP来发起请求,可以通过配置请求重定向,将HTTP请求重定向为HTTPS请求,配置方式如下所示:
在src/main/java路径下创建配置Bean,内容如下:
package com.hongke.config;
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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author chengjunyu
* @classname HttpsConfig
* @description TODO
* @date 2020/7/25 17:27
*/
@Configuration
public class HttpsConfig {
private static final String protocol = "org.apache.coyote.http11.Http11NioProtocol";
@Bean
TomcatServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory webServerFactory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection securityCollection = new SecurityCollection();
securityCollection.addPattern("/");
securityConstraint.addCollection(securityCollection);
context.addConstraint(securityConstraint);
}
};
webServerFactory.addAdditionalTomcatConnectors(newTomcatConnector());
return webServerFactory;
}
private Connector newTomcatConnector() {
//创建一个新的连接,监听设置的端口
Connector connector = new Connector(protocol);
//使用http请求方案
connector.setScheme("http");
//设置一个用来监听的端口号
connector.setPort(9000);
//在setSecure(true)的情况下,只有https才传递到服务器端,http是不会传递的,此处设为false
connector.setSecure(false);
//自定义项目的端口号
connector.setRedirectPort(9001);
return connector;
}
}
上面代码中创建了一中新的http连接方式,端口号为9000,接下来我们通过浏览器地址栏输入localhost:9000/profile/read发起请求,请求成功转发到了https://localhost:9001/profile/read。