【问题标题】:Certificate Based authentication, client share certificate to server基于证书的身份验证,客户端共享证书到服务器
【发布时间】:2020-02-04 09:02:17
【问题描述】:
我有一个服务器应用程序要求共享 SSL 证书。我做的步骤:
- 我针对部署我的应用程序的域 IP 地址(没有域名)生成了一个自签名证书。
- 我将证书共享给服务器。他们会将证书保存在他们的信任库中。
- 服务器正在验证对 IP 地址的请求。如果请求不是来自 IP 地址,他们将阻止它们。
我的问题:
我有一个弹簧启动应用程序。我需要对我生成的证书的代码进行任何更改吗?如果是,那么变化是什么。
【问题讨论】:
标签:
spring-boot
ssl
ssl-certificate
mutual-authentication
【解决方案1】:
是的,您需要对代码进行更改。您需要加载您的密钥库(使用密钥对),如果需要,还将您的信任库加载到您的 http 客户端中。大多数 http 客户端都需要 SSLContext,所以这对您来说就足够了:
KeyStore keyStore = ...;
TrustStore trustStore = ...;
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
// Spring provides by default RestTemplate as HTTP Client, this client is an Apache HTTP Client wrapper
// The setup would be:
HttpClient httpClient = HttpClient.newBuilder();
.sslContext(sslFactory.getSslContext());
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory)