SpringBoot+阿里云ssl完成 http转https以及ws转wss
前言
本文工作是建立在已经有一个SSL证书的基础之上。阿里云证书如何申请可以参考以下链接:
阿里云免费SSL证书申请流程
申请完成后下载相应的证书。本文的服务器是springboot内置的Tomcat服务器,因此选择下载tomcat版本的。
下载完成后解压,会出现一个.pfx
后缀和.txt
后缀的文件。
- 证书文件(domainName.pfx):以
.pfx
为文件类型。 - 密码文件(pfx-password.txt):以
.txt
为文件类型。
一、HTTP转HTTPS
首先将.pfx
后缀的文件,放在springboot项目下的resources
目录下,然后在application.yml
文件配置以下内容。
如果是application.properties
,将其修改为改成application.yml
添加以下配置
server:
port: 8086
ssl:
key-store: classpath:5782771_www.xxxxx.top.pfx
key-store-password: xxxxxx
key-store-type: PKCS12
enabled: true
然后在Springboot的启动类里面添加以下代码:
public class ManageApplication {
public static void main(String[] args) {
SpringApplication.run(ManageApplication.class, args);
}
@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(8078);
connector.setSecure(false);
connector.setRedirectPort(8086);
return connector;
}
}
/* * 在这里设置http的监听端口为8078端口 完成以上配置后,我们访问 http://localhost:8078 即可自动跳转为 https://localhost:8086 之后作测试就可以使用:https://localhost:8086 进行数据请求和页面访问了。 如果部署在阿里云服务器,并且证书绑定了域名www.xxx.com或者ip 就可以使用 https://域名:8086 或者 https://ip:8086 来完成接口数据请求和页面访问 * */
设置完成后,启动项目不报错,且下面显示以下内容说明成功了。
[frame] 2021-09-15 10:44:41,745 - 2398 INFO [main] org.springframework.boot.web.embedded.tomcat.TomcatWebServer:220 - Tomcat started on port(s): 8086 (https) 8078 (http) with context path ''
[frame] 2021-09-15 10:44:41,755 - 2408 INFO [main] org.springframework.boot.StartupInfoLogger:61 - Started ManageApplication in 2.759 seconds (JVM running for 4.215)
二、ws转wss
在springboot的启动类下加上以下代码,就可以通过wss://localhost:8086
进行访问了。
如果部署在阿里云服务器,并且证书绑定了域名www.xxx.com或者ip
就可以使用 wss://域名:8086
或者 wss://ip:8086
来进行websocket的连接。
public static void main(String[] args) {
SpringApplication.run(ManageApplication.class, args);
}
@Bean
public TomcatContextCustomizer tomcatContextCustomizer() {
log.info("init");
return new TomcatContextCustomizer() {
@Override
public void customize(Context context) {
log.info("init customize");
context.addServletContainerInitializer(new WsSci(), null);
}
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)