Nas*_*ann 9 java spring client-certificates x509certificate resttemplate
我想用我的spring应用程序使用REST服务.要访问该服务,我有一个客户端证书(自签名和.jks格式)进行授权.对其他服务进行身份验证的正确方法是什么?
这是我的要求:
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());
}
Run Code Online (Sandbox Code Playgroud)
小智 18
以下是使用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;
}
Run Code Online (Sandbox Code Playgroud)
现在,将使用此模板执行的所有远程调用cert.jks
.
注意:您需要放入cert.jks
类路径
@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());
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19271 次 |
最近记录: |