springboot添加https
命令行需要采用管理员权限(C盘)
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
- -storetype 指定密钥仓库类型
- -keyalg 生证书的算法名称,RSA是一种非对称加密算法
- -keysize 证书大小
- -keystore 生成的证书文件的存储路径
- -validity 证书的有效期
propertites.yml配置
server:
port: 8443
ssl:
key-store: src\main\resources\keystore.p12 keystore.p12为文件名,放入resources文件下
key-store-password: 123456 生成keystore.p12时输入的密码
keyStoreType: PKCS12
keyAlias: tomcat
设置http到https的重定向
@Configuration
public class HttpToHttpsConfig {
@Value("${http.port}")
int httpPort;
@Value("${server.port}")
int httpsPort;
/**
* it's for set http url auto change to https
*/
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = 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);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(httpPort);
connector.setSecure(false);
connector.setRedirectPort(httpsPort);
return connector;
}
}
根据keystore.p12导出客户端证书(双击使用加入电脑的信任列表)
keytool -export -alias tomcat -keystore keystore.p12 -storetype PKCS12 -keypass 123456 -file client.cer