springboot添加ssl实现https访问(http自动跳转)
2022/2/5 6:13:50
本文主要是介绍springboot添加ssl实现https访问(http自动跳转),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目录- Step1
- Step2
- Step3
- Step4
- Step5
Step1
去搞一个证书,我的是腾讯买域名送的
Step2
下载jks格式的
Step3
放到项目的resource目录下的ssl文件夹下(需要new)
Step4
新建配置类,用于自动重定向到https
package club.shengcong.sendemail.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.beans.factory.annotation.Value; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * https配置类 * * @author 金聖聰 * @version v1.0 * @email jinshengcong@163.com * @since Created in 2022/02/04 0:46 */ @Configuration public class HttpsConfiguration { @Value("${http-port}") private int port; @Value("${server.port}") private int sslPort; @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(redirectConnector()); return tomcat; } private Connector redirectConnector() { Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); connector.setScheme("http"); connector.setPort(port); connector.setSecure(false); connector.setRedirectPort(sslPort); return connector; } }
Step5
修改配置类
# https的端口 server.port=443 # SSL证书路径 一定要加上classpath: server.ssl.key-store=classpath:ssl/XXX.jks # SSL证书私钥 server.ssl.key-store-password=XXXX # 证书类型 server.ssl.key-store-type=JKS # http重定向https配置 http-port=80 # 项目路径 server.servlet.context-path=/XXX
Tips: 直接docker部署的时候端口号问题
需要同时开两个端口才能正常访问
-p 80:80 -p 443:443
这篇关于springboot添加ssl实现https访问(http自动跳转)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南
- 2024-09-30Dnd-Kit学习:新手快速入门指南