ssl證書我選擇了免費(fèi)的Let's Encrypt
1.下載腳本并生成證書
# git clone https://github.com/letsencrypt/letsencrypt
# cd letsencrypt
# ./letsencrypt-auto certonly --standalone --email 郵箱 -d 域名
因?yàn)榫W(wǎng)絡(luò)問題pip可能需要換源请毛,請(qǐng)自行網(wǎng)上查找換源方法曼月。
2.設(shè)置自動(dòng)延期
# ./letsencrypt-auto --renew certonly --email 郵箱 -d 域名
3.查看證書
# cd /etc/letsencrypt/live/
# cd 域名
fullchain.pem 為證書 privatkey.pem 為密鑰
4.生成.jks證書
# openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out fullchain_and_key.p12 -name tomcat
# keytool -importkeystore -deststorepass 'yourJKSpass' -destkeypass 'yourKeyPass' -destkeystore MyDSKeyStore.jks -srckeystore fullchain_and_key.p12 -srcstoretype PKCS12 -srcstorepass 'yourPKCS12pass' -alias tomcat
第一步會(huì)讓你輸入密碼妻柒,對(duì)應(yīng)第二步中的yourPKCS12pass 。第二步中的前兩個(gè)密碼自己設(shè)置一下并記好焚刚,下面的會(huì)用到濒蒋。
5.配置spring-boot
將.jsk文件放到resources
文件夾下然后在配置文件中加上
server.port = 8443
server.ssl.key-store = classpath:MyDSKeyStore.jks
server.ssl.key-store-password = yourJKSpass
server.ssl.key-password = yourKeyPass
此時(shí)服務(wù)器支持https,但只支持https
可以配置同時(shí)支持htttp
@Bean
public Integer port() {
return 8080;
//return SocketUtils.findAvailableTcpPort();
}
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(port());
return connector;
}
這樣 8080端口是http 8443端口是https
也可以設(shè)置http自動(dòng)重定向到https
@Value("${server.port}")
private int port;
@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(port);
return connector;
}