springboot配置SSL自签名证书

1.证书生成

每一个JDK或者JRE里都有一个工具,叫做:keytool,安装了jdk或jre之后,配置好JAVA环境之后,就可以直接在控制台使用该命令生成自签名证书:

在控制台输入:

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore E:\Desktop\sslkey\keystore.p12 -validity 3650

命令参数说明:

1.-alias 证书别名

2.-storetype 指定密钥仓库类型

3.-keyalg 生证书的算法名称,RSA是一种非对称加密算法

4.-keysize 证书大小

5.-keystore 生成的证书文件的存储路径和文件名

6.-validity 证书的有效期

2.Spring Boot配置SSL

将证书复制到项目根目录,修改application.properties文件:

server.port=8443
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=123456
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=tomcat

到这一步,已经可以通过HTTPS来访问Web了

3.HTTP自动转向HTTPS

在spring boot入口类中添加如下代码:

①spring boot1.x的配置:

// http转向https
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@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;
}

@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}

②springboot 2.x的配置:

@Bean

public TomcatServletWebServerFactory tomcatServletWebServerFactory(){

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;

}

@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}

上一篇:day35-python 操作memcache二


下一篇:Centos7使用kubeadm 安装多主高可用kubernets:v.1.11集群