【问题标题】:How to make REST Get request using certificate?如何使用证书发出 REST Get 请求?
【发布时间】:2017-10-30 03:27:54
【问题描述】:

我可以使用 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 将其导入

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多