mkcert(Windows環境) 1.下載地址:https://github.com/FiloSottile/mkcert/releases 2.選擇版本 3.以管理員身份運行`命令提示符 1) cd C:/ #進入工具存放的目錄下 2) mkcert-v1.4.4-windows-amd64.e ...
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自動會跳轉上條地址
*帶上小鎖是不是很有安全感呢~~~~*
感謝閱讀!