基于mkcert工具实现Spring Boot 项目服务通过Https方式访问
2023-03-31 11:06:49 时间
mkcert(Windows环境)
1.下载地址:https://github.com/FiloSottile/mkcert/releases
2.选择版本
3.以管理员身份运行`命令提示符
1) cd C:/ #进入工具存放的目录下
2) mkcert-v1.4.4-windows-amd64.exe -install #命令进行安装
3) mkcert-v1.4.3-windows-amd64.exe #查询是否安装成功
4) mkcert-v1.4.3-windows-amd64.exe -pkcs12 [本地ip] #为本地ip创建p12证书,生成的证书在当前目录
Spring Boot项目配置证书
1.将p12证书存放在项目resources目录下
2.在pom.xml文件中增加配置
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include> <!--将resources下所有目录文件都打包target文件夹中 -->
</includes>
<filtering>true</filtering>
</resource>
3.配置application.yml
server:
port: 9002
ssl:
key-store: classpath:172.20.10.4.p12
key-password: changeit # mkcert工具生成时默认密码
key-store-password: changeit # mkcert工具生成时默认密码
key-store-type: PKCS12
4.在启动类中增加如下代码
@Bean
public ServletWebServerFactory servletContainer() {
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(initiateHttpConnector());
return tomcat;
}
/**
* 让我们的应用支持HTTP是个好想法,但是需要重定向到HTTPS,
* 但是不能同时在application.yml中同时配置两个connector,
* 所以要以编程的方式配置HTTP connector,然后重定向到HTTPS connector
* @return Connector
*/
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80); // http端口
connector.setSecure(false);
connector.setRedirectPort(9002); // application.yml中配置的https端口
return connector;
}
配置至此结束
启动项目访问地址为:https://ip:port/
或者使用: http://ip:80自动会跳转上条地址
带上小锁是不是很有安全感呢~~~~
感谢阅读!
相关文章
- 深入理解HTTPS原理、过程与实践
- 深入研究Kubernetes的资源请求和限制
- 无服务端编程服务推荐(前端必备)
- PHP协程实现过程详解
- 一篇带给你 Sentinel 和常用流控算法
- 关于PHP的错误机制总结
- 第一次和喜欢的女生吃饭去哪好?
- OpenCV中的KMeans算法介绍与应用
- 教大家如果搭建一套phpstorm+wamp+xdebug调试PHP的环境
- CentOS下三种PHP拓展安装方法
- Go语言HTTP Server源码分析
- 详解Go可用性(六) 熔断
- Go语言HTTP Server源码分析
- 2017年4月编程语言排行榜:Hack首次进入前五十
- 盘点常用语言HTTP请求客户端的惊艳框架
- 50 万行 Go 代码,美国一组织从 Python 2 迁移到 Go
- 从代码层读懂Java HashMap的实现原理
- 谷歌的最新NLP模型,现在能陪你从诗词歌赋谈到人生哲学
- 不要再天天写表单了,淘宝大牛教你零基础写PHP扩展
- Java Web模板代码生成器的设计与实现