spring boot 中启用 https

背景

年末公司要进行年终促销. 上一周时间都在弄年底促销的玩意. 因为用到了第三方的交易服务. 他们的 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;
	}

到这里就全部结束了. 

转载于:https://my.oschina.net/hanbin/blog/782391

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值