1、本地环境运行cmd命令生成测试证书:
keytool -genkey -alias tomcat -keyalg RSA -keystore D:/workspace-dms/dms-parent/dms-web/src/main/resources/server.keystore
密码设置为123456
2、application.properties配置如下:
server.port=8090
server.ssl.key-store=classpath:key/server.keystore
server.ssl.key-alias=tomcat
server.ssl.enabled=true
server.ssl.key-store-password=123456
server.ssl.key-store-type=JKS
3、springboot入口类添加如下代码(注意:适用springboot 2.X以上版本):
@Bean
public Connector connector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setSecure(false);
connector.setPort(8080);
connector.setRedirectPort(8090);
return connector;
}
@Bean
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;
}
4、pom.xml配置如下:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
</build>
如果不设置filtering为false,则证书在springboot项目启动编译时,复制证书到class目录被损坏,报java.io.IOException: Invalid keystore format异常
5、项目访问http://127.0.0.1:8080/dms-web/login自动转为如下地址: