生成证书
利用java生成证书命令:window cmd窗口进入java bin目录
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
image.png
image.png
配置证书
Springboot项目配置证书,其它项目自行搜索相应的配置方法
application.properties 配置 。keystore.p12放入项目根路径。
server.port=8081
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=123456
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias:tomcat
image.png
Http重定向Https
我们希望原来的http请求能自动重定向到最新的Https请求地址,从而避免客户端更改相应的接口地址:
package com.didispace;
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.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import com.sun.org.apache.bcel.internal.classfile.Method;
@SuppressWarnings("unused")
@SpringBootApplication
public class ChapterApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ChapterApplication.class, args);
}
// protected SpringApplicationBuilder configure(SpringApplicationBuilder
// application) {
// return application.sources(ChapterApplication.class);
// }
@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(initiateHttpConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector(
"org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8081);
return connector;
}
}
image.png
发现问题
-
Http重定向Https的时候,端口号不能相同,否者启动项目的时候会报 端口占用 的异常错误;
Http重定向Https POST请求失败 - Http重定向Https的时候,Get请求是没有任何问题的。但是一旦重定向为POST请求的时候,就会报405请求方法不支持的错误。原因在于重定向的时候,Get请求没有转化为对应的POST请求。用如下方法可以解决这个问题(此方法是错误的):
https://stackoverflow.com/questions/42108498/redirect-post-method-http-https-http-status-405-spring-boot
SecurityCollection collection = new SecurityCollection();
collection.addMethod("post"); //添加post方法
collection.addPattern("/*");
验证成功:
Http重定向Https之post请求
网友评论