在spring中每个请求都发送一个客户端证书的正确方法是什么?
问题描述:
我想用我的spring应用程序来使用REST服务。要访问该服务我有一个客户端证书(自签名和.jks格式)授权。 什么是对其他服务进行身份验证的正确方法?在spring中每个请求都发送一个客户端证书的正确方法是什么?
这是我的要求:
public List<Info> getInfo() throws RestClientException, URISyntaxException {
HttpEntity<?> httpEntity = new HttpEntity<>(null, new HttpHeaders());
ResponseEntity<Info[]> resp = restOperations.exchange(
new URI(BASE_URL + "/Info"), HttpMethod.GET,
httpEntity, Info[].class);
return Arrays.asList(resp.getBody());
}
答
下面是例子,如何做到这一点使用RestTemplate和Apache HttpClient
你应该定义自己的RestTemplate
与配置SSL上下文:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {
char[] password = "password".toCharArray();
SSLContext sslContext = SSLContextBuilder.create()
.loadKeyMaterial(keyStore("classpath:cert.jks", password), password)
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
HttpClient client = HttpClients.custom().setSSLContext(sslContext).build();
return builder
.requestFactory(new HttpComponentsClientHttpRequestFactory(client))
.build();
}
private KeyStore keyStore(String file, char[] password) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
File key = ResourceUtils.getFile(file);
try (InputStream in = new FileInputStream(key)) {
keyStore.load(in, password);
}
return keyStore;
}
现在此模板执行的所有远程呼叫都将使用cert.jks
进行签名。 注意:你会需要把cert.jks
到你的classpath
@Autowired
private RestTemplate restTemplate;
public List<Info> getInfo() throws RestClientException, URISyntaxException {
HttpEntity<?> httpEntity = new HttpEntity<>(null, new HttpHeaders());
ResponseEntity<Info[]> resp = restTemplate.exchange(
new URI(BASE_URL + "/Info"), HttpMethod.GET,
httpEntity, Info[].class);
return Arrays.asList(resp.getBody());
}
的伟大工程的感谢! – Nas3nmann