JAVA 自制https 证书
SpringBoot2.x配置HTTPS访问,总体上可以分为两大步:一.生成SSL证书;二.配置HTTPS访问。
打开cmd命令窗口
keytool -genkey -alias tomcat -keyalg RSA -keysize 2048 -validity 365 --keystore F:/tomcat.keystore -keypass 12345678 -storepass 12345678
-alias tomcat (别名,配置文件会用到这个名字)
过程如下:提示问题的回答可以任意填写
在F盘生成了tomcat.keystore文件:
查看keystore中证书条目列表
2 配置项目 ,
把证书放入项目跟目录,跟pom.xml 同一级
配置文件
server:
port: 443
ssl:
key-store: tomcat.keystore
key-store-password: w
key-store-type: JKS
key-alias: tomcat
然后新建配置类
package com.invoice.project.config;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
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.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("pro")
public class HttpsConfigure {
@Bean
public ServletWebServerFactory servletWebServerFactory() {
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(redirectConnector());
return factory;
}
private Connector redirectConnector() {
Connector connector = new Connector(Http11NioProtocol.class.getName());
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
}