SpringBoot配置Https入门实践
作者:qinxun2008081
本文主要介绍了SpringBoot配置Https入门实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一、生成一个https证书
我们使用Java自带的JDK管理工具keytool来生成一个免费的https证书,在我们的Java安装目录下,在bin目录下我们使用cmd启动命令行窗口,执行如下命令生成一个https证书。
keytool -genkey -alias myhttps -keyalg RSA -keysize 2048 -keystore E:\test.p12 -validity 365
- genkey表示要创建一个新的密钥
- alias表示keystore的别名
- keyalg表示使用的加密算法是RSA
- keysize表示密钥的长度
- keystore表示生成密钥的存放位置
- validity表示密钥的有效天数

我们设置的密钥的名称是myhttps,口令是123456,先保存好后续集成到SpringBoot会使用到。

我们在E盘中发现生成了这个https证书。
二、集成到SpringBoot
1.把生成的https证书复制到项目的resources目录下

2.在application.yml中添加https相关配置
server:
ssl:
# 证书文件名
key-store: classpath:test.p12
# 证书密钥别名
key-alias: myhttps
# 密钥口令
key-store-password: 1234563.启动项目测试
示例代码如下:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author qinxun
* @date 2023-06-15
* @Descripion:
*/
@RestController
public class IndexController {
@GetMapping("/index")
public String toIndex() {
return "hello https";
}
}我们先使用常规的http访问,会提示请求错误。

我们修改为使用https访问,可以正常访问了。

三、请求转发配置
SpringBoot不支持同时启用http和https,为了解决这个问题,我们可以新增一个配置,当用户发起http访问的时候,自动重定向到https上。
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 qinxun
* @date 2023-06-16
* @Descripion: 请求转发配置
*/
@Configuration
public class HttpsConfig {
@Bean
TomcatServletWebServerFactory tomcatServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
factory.addAdditionalTomcatConnectors(createHttpsConnector());
return factory;
}
private Connector createHttpsConnector() {
// 设置http请求端口为8081的都自动重定向到https端口
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8081);
connector.setSecure(false);
connector.setRedirectPort(8080);
return connector;
}
}我们请求http://localhost:8081/index会重定向到了https://localhost:8080/index这个访问地址,成功实现了http重定向到https的配置。
到此这篇关于SpringBoot配置Https入门实践的文章就介绍到这了,更多相关SpringBoot配置Https内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
