文章目录
功能背景
最近我们项目很多依赖API纷纷上Azure,通过Azure的Application Gateway 服务进行负载均衡处理切采用双向认证。因此我们就需要考虑证书的出示与信任问题,捣鼓了好久,在我差点儿要吐的情况下……还好成功解决了。
角色介绍
- 服务器: Azure Gateway
- 客户端: HttpClient
因为是我们请求Azure Gateway 服务从而请求对应API,所以其就是Server端,相对应的我们就是Client端。
服务器端证书获取
直接在浏览器中访问Gateway URL ,即可获取服务器端证书。详细步骤参考我的文章网站证书获取
Gateway 信任客户端证书
好了,到此我们已经有了服务器端的证书,我们可以信任服务器端证书,那么我们还需要准备我们的证书给Gateway信任,这样彼此信任方为双向认证嘛。^ -^
OpenSSL对d证书文件处理
到目前为止,我们与Gateway彼此信任,就可以通信了。 但是如果要使用HttpClient还需要一些处理。这里我们使用OpenSSL(关于OpenSSL有时间我另写一篇介绍)对证书进行处理。
证书文件生成JKS文件
在OpenSSL中使用下面的命令
Server端证书处理
keytool -import -alias csdncert -keystore trustkeystore.jks -file D:/csdn.cer -storepass changeit
Client端证书处理
Client端证书有一点比较特殊,我们需要使用我们的私钥。
openssl pkcs12 -export -name myservercert -in myserver.cer –inkey myserver.key -out myserver.p12
证书文件生成P12文件
在OpenSSL中使用下面的命令
Server端证书处理
keytool -importkeystore -destkeystore trustkeystore.jks -srckeystore trustkeystore.p12 -srcstoretype pkcs12 -alias trustkeystore
Client端证书处理
Client端证书有一点比较特殊,我们需要使用我们的私钥。
keytool -importkeystore -destkeystore myserver.jks -srckeystore myserver.p12 -srcstoretype pkcs12 -alias myserver
HttpClient双向认证(Mutual Authentication )实现
public static String doPostJsonWithMutualSSL(String url, String params,String certSystemName) throws Exception{
RequestConfig config = RequestConfig.custom().setConnectTimeout(3000)
.setSocketTimeout(3000).build();
SSLContext sslContext = buildSSLContextForWAS();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext, new String[] {
"TLSv1.2", "TLSv1.1",