生成密钥文件
keytool -genkeypair -alias adminstore -keyalg RSA -keysize 2048 -keypass 123456 -storetype JKS -keystore /Users/lwpeng/adminstore.jks -storepass 123456 -validity 3650
配置application.properties
server.ssl.enabled=true
server.ssl.key-store=classpath:adminstore.jks
server.ssl.key-store-type=JKS
server.ssl.key-store-password=123456
预览效果
http://localhost:9999/swagger-ui/index.html (提示错误)
https://localhost:9999/swagger-ui/index.html (正常访问)
集成成功
http协议访问自动跳转
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;
/**
* @ClassName HttpsConfig
* @Description: TODO
* @Author lwpeng
* @Date 2022/11/1
* @Version V1.0
**/
@Configuration
public class HttpsConfig {
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection securityCollection = new SecurityCollection();
securityCollection.addPattern("/*");
securityConstraint.addCollection(securityCollection);
context.addConstraint(securityConstraint);
}
};
factory.addAdditionalTomcatConnectors(httpConnector());
return factory;
}
@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(9999);
return connector;
}
}
预览效果
http://localhost/swagger-ui/index.html (正常访问)