spring 中 resttemplate 发出的每个请求发送客户端证书的正确方法是什么?

What is the right way to send a client certificate with every request made by the resttemplate in spring?

我想在我的 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());
}

这是如何使用 RestTemplate and Apache HttpClient

执行此操作的示例

您应该使用已配置的 SSL 上下文定义您自己的 RestTemplate

@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 放入您的类路径

@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());
}

或者您可以只将证书导入您的 JDKs cacerts,所有使用 jdk(在您的情况下为 rest 模板)的 HTTP 客户端都将使用该证书进行 REST 调用。

keytool -import -keystore $JAVA_HOME/jre/lib/security/cacerts -file foo.cer -alias alias

P.S: 导入成功后不要忘记重启服务器。密钥库的默认密码 - changeit