1. 获取 SSL 证书
Spring Boot 配置SSL证书用百度云的ssl证书来举例,首先从百度云下载下来pfx格式的证书

2.接下来我们在springboot的配置文件里配置一下证书的地址
#服务设定
server:
# 端口 使用HTTPS默认端口
port: 443
#HTTPS加密配置
ssl:
#证书路径
key-store: classpath:xxxxx.pfx
#证书密码
key-store-password: xxxx
3.配置输入http的端口,自动跳转到https的路径
package com.tms.tblog;
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.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@MapperScan("com.tms.tblog.dao")
@EnableWebMvc
public class TBlogApplication {
public static void main(String[] args) {
SpringApplication.run(TBlogApplication.class, args);
}
/**
* http 转 https
*/
@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
// 监听的http端口
connector.setPort(8080);
connector.setSecure(false);
// 监听到http端口后跳转的https端口
connector.setRedirectPort(443);
return connector;
}
/**
* 拦截所有的请求
*/
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
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(connector);
return tomcat;
}
}
上述配置类将 HTTP 请求(端口 8080)重定向到 HTTPS 请求(端口 8443)。 通过以上步骤,你就可以在 Spring Boot 应用中成功配置 SSL 证书,实现 HTTPS 安全访问。
评论