如何使用证书进行REST获取请求?

时间:2017-10-30 03:27:55

标签: java spring resttemplate client-certificates spring-rest

我可以使用curl查询获取请求:

curl -k --key some.key --cert some.crt --url "https://app.com:7078/subscribers/checkExists/1"

在该查询之后,我得到200 OK响应。我如何在Java中实现同样的目标?使用Spring RestTemplate

我试图通过互联网上的手册禁用认证检查:

CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

ResponseEntity<String> response = null;
String urlOverHttps = "https://app.com:7078/subscribers/checkExists/1";
response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);

我也是通过@Configuration尝试的:

@Bean
public boolean disableSSLValidation() throws Exception {
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }}, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    return true;
}

该代码回复了我400 Bad Request错误。

UPD

我还将some.crt文件添加到%JAVA_HOME%\lib\security并使用命令导入 - keytool -import -alias ca -file some.crt -keystore cacerts -storepass changeit

那么,如何使用some.crtGET请求中提供我的Spring RestTemplate文件?

1 个答案:

答案 0 :(得分:0)

您需要将密钥添加到Java密钥库(JKS)。请参阅此处找到的关于使用keytool导入密钥的答案:

How to import an existing x509 certificate and private key in Java keystore to use in SSL?