mkcert(Windows环境)
1.下载地址:https://github.com/FiloSottile/mkcert/releases
2.选择版本
3.以管理员身份运行`命令提示符
1) cd C:/ #进入工具存放的目录下
2) mkcert-v1.4.4-windows-amd64.exe -install #命令进行安装
3) mkcert-v1.4.3-windows-amd64.exe #查询是否安装成功
4) mkcert-v1.4.3-windows-amd64.exe -pkcs12 [本地ip] #为本地ip创建p12证书,生成的证书在当前目录
Spring Boot项目配置证书
1.将p12证书存放在项目resources目录下
2.在pom.xml文件中增加配置
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include> <!--将resources下所有目录文件都打包target文件夹中 -->
</includes>
<filtering>true</filtering>
</resource>
3.配置application.yml
server:
port: 9002
ssl:
key-store: classpath:172.20.10.4.p12
key-password: changeit # mkcert工具生成时默认密码
key-store-password: changeit # mkcert工具生成时默认密码
key-store-type: PKCS12
4.在启动类中增加如下代码
@Bean
public ServletWebServerFactory servletContainer() {
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(initiateHttpConnector());
return tomcat;
}
/**
* 让我们的应用支持HTTP是个好想法,但是需要重定向到HTTPS,
* 但是不能同时在application.yml中同时配置两个connector,
* 所以要以编程的方式配置HTTP connector,然后重定向到HTTPS connector
* @return Connector
*/
private Connector initiateHttpConnector() {
Connector connector = new Connector(\"org.apache.coyote.http11.Http11NioProtocol\");
connector.setScheme(\"http\");
connector.setPort(80); // http端口
connector.setSecure(false);
connector.setRedirectPort(9002); // application.yml中配置的https端口
return connector;
}
配置至此结束
启动项目访问地址为:https://ip:port/
或者使用: http://ip:80自动会跳转上条地址
*带上小锁是不是很有安全感呢~~~~*
感谢阅读!
来源:https://www.cnblogs.com/zklymm/p/16356119.html
本站部分图文来源于网络,如有侵权请联系删除。