简体   繁体   English

如何使用带有证书认证的 RestTemplate?

[英]How to use RestTemplate with certificate authentication?

I have an endpoint which requires SSL authentication.我有一个端点需要 SSL 身份验证。 I'm able to successfully post a request on that endpoint with:我能够通过以下方式在该端点上成功发布请求:

curl --location --request POST 'https://someurl.click' --header 'some headers' --cert my_cert.pem

I need to create a Spring Boot application which POSTs a request to that endpoint using that certificate with RestTemplate.我需要创建一个 Spring 引导应用程序,它使用带有 RestTemplate 的证书向该端点发送请求。 I've read that PEM certificates are not valid and I need to use p12 or JKS.我读到 PEM 证书无效,我需要使用 p12 或 JKS。

So I converted my certificate to p12 with:所以我将我的证书转换为 p12:

openssl pkcs12 -export -in my_cert.pem -out my_cert.p12

And used it as a Trust Store in my Bean as suggested by several references (where trustStore points to the converted p12 certificate):并按照多个参考文献的建议将其用作我的 Bean 中的信任库(其中 trustStore 指向转换后的 p12 证书):

    @Value("${trust-store}")
    private Resource trustStore;

    @Value("${trust-store-password}")
    private String trustStorePassword;

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = new SSLContextBuilder()
        .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
        .build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(socketFactory)
        .build();

    return builder
        .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
        .build();
    }

When using this RestTemplate I'm having SSL handshake errors.使用此 RestTemplate 时出现 SSL 握手错误。

Code:代码:

String response = restTemplate.postForObject(myEndpoint, request, String.class);

Output: Output:

2021-08-04 12:06:41.926 ERROR 129727 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://myurl.click": readHandshakeRecord; nested exception is javax.net.ssl.SSLException: readHandshakeRecord] with root cause

java.net.SocketException: Broken pipe (Write failed)
        at java.base/java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:na]
        at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110) ~[na:na]
        at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150) ~[na:na]
        at java.base/sun.security.ssl.SSLSocketOutputRecord.encodeChangeCipherSpec(SSLSocketOutputRecord.java:221) ~[na:na]
        at java.base/sun.security.ssl.OutputRecord.changeWriteCiphers(OutputRecord.java:162) ~[na:na]
        at java.base/sun.security.ssl.ChangeCipherSpec$T10ChangeCipherSpecProducer.produce(ChangeCipherSpec.java:118) ~[na:na]
        at java.base/sun.security.ssl.Finished$T12FinishedProducer.onProduceFinished(Finished.java:395) ~[na:na]
        at java.base/sun.security.ssl.Finished$T12FinishedProducer.produce(Finished.java:379) ~[na:na]...

Any advice is greately appreciated.非常感谢任何建议。

I was able to make it work by using a JKS keystore instead of a p12 certificate.我能够通过使用 JKS 密钥库而不是 p12 证书来使其工作。

First, I used the private key and both private and public keys as an input to generate a P12 certificate:首先,我使用私钥以及私钥和公钥作为输入来生成 P12 证书:

openssl pkcs12 -export -inkey <private_key>.pem -in <all_keys>.pem -name new_certificate -out certificate.p12

Finally, I converted the P12 certificate into a JKS keystore using keytool:最后,我使用 keytool 将 P12 证书转换为 JKS 密钥库:

keytool -importkeystore -srckeystore certificate.p12 -srcstoretype pkcs12 -destkeystore certificate.jks

Then, I could finally load it in a RestTemplate instance using SSLContext:然后,我终于可以使用 SSLContext 将它加载到 RestTemplate 实例中:

@Value("${trust-store}")
    private String trustStore;
    @Value("${trust-store-password}")
    private String trustStorePassword;

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {
        Resource trustStoreCertificate = new ClassPathResource(trustStore);
        File certificate = new File("combined.jks");
        FileUtils.copyInputStreamToFile(trustStoreCertificate.getInputStream(), certificate);
        SSLContext sslContext = new SSLContextBuilder()
        .loadKeyMaterial(certificate , trustStorePassword.toCharArray(), trustStorePassword.toCharArray()).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(socketFactory)
        .build();

    certificate.delete();

    return builder
        .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
        .build();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM