spring boot改成https请求
在linux控制台执行keytool -genkey -keystore keystore.p12 -storePass 123456-storetype PKCS12 -keyalg RSA -alias tomcat -keypass 123456-validity 3650关于这几个参数的解释如下:1.-storetype 指定密钥仓库类型2.-keyalg 生证书的算法名称,RSA是一种非
在linux控制台执行
keytool -genkey -keystore keystore.p12 -storePass 123456 -storetype PKCS12 -keyalg RSA -alias tomcat -keypass 123456 -validity 3650
关于这几个参数的解释如下:
1.-storetype 指定密钥仓库类型
2.-keyalg 生证书的算法名称,RSA是一种非对称加密算法
3.-keysize 证书大小
4.-keystore 生成的证书文件的存储路径
5.-validity 证书的有效期
如果是下面的执行命令需要输入密钥库口令
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
依次填写证书相关的信息即可生成证书。
系统的当前用户目录下会生成一个keystore.p12文件,当然你在生成证书的时候可以改变证书的名称,那么相应的系统用户目录下就会生成相应的文件,将keystore.p12文件拷贝到我们项目的根路径下,默认是读取根目录下。也可以调整为别的目录,我的放在src/main/resources/。
接着调整application.yml:
server:
port: 8080
ssl:
key-store: src/main/resources/keystore.p12
key-store-password: 123456
keyStoreType: PKCS12
keyalg: RSA
keyAlias: tomcat
enabled: true
再运行服务后,访问web就是https方式了。
http重定向到https ,在启动类上增加以下代码:
@Bean
public ServletWebServerFactory 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(createHTTPConnector());
return tomcat;
}
private Connector createHTTPConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//同时启用http(8081)、https(8080)两个端口
connector.setScheme("http");
connector.setSecure(false);
connector.setPort(8081); //自定义
connector.setRedirectPort(8080); //对应application.yml的port
return connector;
}
参考:

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)