1. Generate a certificate, which can be self-signed or obtained from an SSL certificate authority.
Keytool in JDK is a certificate management tool that can generate self-signed certificates.
The generated command is as follows (if you can't find the keytoo command, go to configure the java environment first)
The name I specified is tomcat.keystore, alias tomcat, and the password is set by yourself. I use tomcat here, and the last one just press Enter.
keytool -genkey -alias tomcat -keyalg RSA -keystore D:/tomcat.keystore
2. SpringBoot configure SSL
Copy this tomcat.keystore to the project root directory (project root directory, for example, my idea project is called meatball-parent, and then my module is called meatball-admin, so our certificate should be placed under meatball-parent)
3. Let the post configuration application.yml
server:
port: 443 #配置端口号
#port: 12580
ssl:
# 证书名称
key-store: yikatong.keystore
#密钥库密码
key-store-password: P@ssw0rd
key-store-type: JKS
key-alias: yikatong
Now start the project and enter https://localhost /
Usually, entering http://www.baidu.com will automatically jump to https. The implementation is as follows:
package com.meatball.component;
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.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Https转换
*/
@Configuration
public class HttpsComponent {
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
//confidential
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(80);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
}
At this point, run http://localhost , it will automatically jump to https://localhost