700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > springboot配置SSL证书设置https协议访问的端口

springboot配置SSL证书设置https协议访问的端口

时间:2021-09-14 17:45:02

相关推荐

springboot配置SSL证书设置https协议访问的端口

配置SSL证书需要证书文件 和 密钥

1. 将证书文件移动到resources目录下

2. 在yml配置文件中配置如下:

server:port: 443 #服务端口ssl:key-store: classpath:.pfx #SSL证书存放的位置key-store-password: TzkIG1k1 #密钥key-store-type: PKCS12 #证书的类型my:httpPort: 9000httpsPort: 443

效果图参考如下:

3. 创建一个配置文件HttpToHttpsConfig.java

该配置的主要作用就是将所有的http请求重定向到https上进行操作,也就是说即使你访问http://127.0.0.1:80 也会重定向到https://127.0.0.1:80 。

这里说一个题外话(https的默认端口是443端口)

HttpToHttpsConfig配置类代码如下(无序改动):

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.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/*** 连接器配置 配置http向https的重定向,即使前端依然访问http,也会被定向到https*/@Configurationpublic class HttpToHttpsConfig {@Value("${server.my.httpPort}")private int httpPort;@Value("${server.my.httpsPort}")private int httpsPort;/*** http重定向到https* @return*/@Beanpublic TomcatServletWebServerFactory servletContainer() {TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {@Overrideprotected void postProcessContext(Context context) {SecurityConstraint constraint = new SecurityConstraint();constraint.setUserConstraint("CONFIDENTIAL");SecurityCollection collection = new SecurityCollection();collection.addPattern("/*");constraint.addCollection(collection);context.addConstraint(constraint);}};tomcat.addAdditionalTomcatConnectors(httpConnector());return tomcat;}@Beanpublic Connector httpConnector() {Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setScheme("http");//Connector监听的http的端口号connector.setPort(httpPort);connector.setSecure(false);//监听到http的端口号后转向到的https的端口号connector.setRedirectPort(httpsPort);return connector;}}

4. 启动项目

https协议端口是433端口 , http协议的端口是9000

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。