背景
年末公司要进行年终促销. 上一周时间都在弄年底促销的玩意. 因为用到了第三方的交易服务. 他们的 webhook 要求接口必须是 https. 之前没有自己搞过 https. 刚好学习, 然后记录下来.
获取证书
https 是加密链接. 是需要证书的. 那么证书从哪里取得呢? 在本地测试的时候, 可以自己生成一个 tomcat 的证书, 可以本地测试用.
生成方式配置方式见下面.
keytool -genkey -v -alias mykey -keyalg RSA -validity 3650 -keystore ./keystore
server.port:8443
server.ssl.key-store: classpath:keystore.p12
server.ssl.key-store-password: xxxxx
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
但是本地生成的证书在生产环境是没法用的. 第三方调用的时候是不 OK 的.
于是, 在阿里云上找到了免费的证书申请.
购买后, 会有邮件发到注册邮箱来认证的. 当然, 这里要注意这个免费的证书只能用在一个域名下.
(不知道为什么用公司邮箱和个人邮箱, 这里给出的认证方式不同. )
spring boot 配置
证书生成好之后, 下载之. 然后放在resources目录下. 和 application.properties 并列.
阿里云这个下载下来默认是pfx 格式的. 按照下面这样配置就行:
server.ssl.key-store=classpath:1111111.pfx
server.ssl.key-store-password=1111111
server.ssl.keyStoreType=PKCS12
因为是生产环境, 需要做 http 自动转到 https. 所以这里不配置端口号.
http 自动转到 https
生产环境上 http 转到 https 是一个很必要的能力.
在 spring boot 的启动类中. 添加如下代码即可
@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(80);
connector.setRedirectPort(443);
connector.setSecure(false);
return connector;
}
到这里就全部结束了.