SpringBoot可以直接配置https,如果是小型项目,可以不用使用tomcat或者nginx配置ssl。
好,咱们先配置下application.yaml。
server:
session-timeout: 1800
port: 443
ssl:
key-store: /home/ssl/www.youcaibang.cn.jks
key-store-password: 123456
key-store-type: JKS
enabled: true
划重点了,上面的代码只解决了https开头的80,443访问。
下面我们加一个配置类,将http的访问映射到443。
package com.bootdo.system.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.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TomcatConfiguration {
@Bean
TomcatServletWebServerFactory tomcatServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
factory.addAdditionalTomcatConnectors(createTomcatConnector());
return factory;
}
private Connector createTomcatConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
}
这样才解决http开头的80和443访问。
划重点了!!!最重要的是,放开服务器的443端口。
以阿里云为例,千万不要忘记了。
想要了解更多的同学们,请关注下我的公众号哟。