首先是要申请 ssl 证书,阿里有免费的,进入控制台,查询证书,按步骤操作,申请速度挺快的
审核通过后,证书有好几个,下载 tomcat 的证书,解压后有一个 pfx 文件和一个密码文件。
把 pfx 文件放在一个目录下,我是放在 /root/as/ 目录下,PKCS12 是算法,不用改
application.properties 配置文件,填写路径和密码
server.port=443
server.ssl.key-store=/root/as/30233_baidu884.com.pfx
server.ssl.key-store-password=123456
server.ssl.key-store-type=PKCS12
再增加两个 Bean,我使用了条件,这样开发环境可以是8080 或别的http端口,只在生产环境才使用 https
@Bean
@ConditionalOnExpression("'${server.port}'==443")
public Connector connector()
{
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(serverPort);
return connector;
}
@Bean
@ConditionalOnExpression("'${server.port}'==443")
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;
}
如果我的文章对你有用,请点个赞吧