我在两台不同的机器上拥有两个基于 Spring 的 Web 应用程序 A 和 B。
我想从 Web 应用程序 A 向 Web 应用程序 B 进行 HTTPS 调用,但是,我在机器 B 中使用自签名证书。所以我的 HTTPS 请求失败。
在 Spring 中使用 RestTemplate 时如何禁用 HTTPS 证书验证?我想禁用验证,因为 Web 应用 A 和 B 都在内部网络中,但数据传输必须通过 HTTPS 进行
我在两台不同的机器上拥有两个基于 Spring 的 Web 应用程序 A 和 B。
我想从 Web 应用程序 A 向 Web 应用程序 B 进行 HTTPS 调用,但是,我在机器 B 中使用自签名证书。所以我的 HTTPS 请求失败。
在 Spring 中使用 RestTemplate 时如何禁用 HTTPS 证书验证?我想禁用验证,因为 Web 应用 A 和 B 都在内部网络中,但数据传输必须通过 HTTPS 进行
@Bean
public RestTemplate restTemplate()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
本质上,您需要做的两件事是使用信任所有证书的自定义 TrustStrategy,并使用NoopHostnameVerifier()禁用主机名验证。这是代码,包含所有相关的导入:
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
您需要添加的是自定义HostnameVerifier
类绕过证书验证并返回 true
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
这需要适当地放置在您的代码中。
用 cookie 添加我的回复:
public static void main(String[] args) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("username", testUser);
params.add("password", testPass);
NullHostnameVerifier verifier = new NullHostnameVerifier();
MySimpleClientHttpRequestFactory requestFactory = new MySimpleClientHttpRequestFactory(verifier , rememberMeCookie);
ResponseEntity<String> response = restTemplate.postForEntity(appUrl + "/login", params, String.class);
HttpHeaders headers = response.getHeaders();
String cookieResponse = headers.getFirst("Set-Cookie");
String[] cookieParts = cookieResponse.split(";");
rememberMeCookie = cookieParts[0];
cookie.setCookie(rememberMeCookie);
requestFactory = new MySimpleClientHttpRequestFactory(verifier,cookie.getCookie());
restTemplate.setRequestFactory(requestFactory);
}
public class MySimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private final HostnameVerifier verifier;
private final String cookie;
public MySimpleClientHttpRequestFactory(HostnameVerifier verifier ,String cookie) {
this.verifier = verifier;
this.cookie = cookie;
}
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setHostnameVerifier(verifier);
((HttpsURLConnection) connection).setSSLSocketFactory(trustSelfSignedSSL().getSocketFactory());
((HttpsURLConnection) connection).setAllowUserInteraction(true);
String rememberMeCookie = cookie == null ? "" : cookie;
((HttpsURLConnection) connection).setRequestProperty("Cookie", rememberMeCookie);
}
super.prepareConnection(connection, httpMethod);
}
public SSLContext trustSelfSignedSSL() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLContext.setDefault(ctx);
return ctx;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
public class NullHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
我找到了一个简单的方法
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
使用的进口
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
您可以将其与 HTTPClient API 一起使用。
public RestTemplate getRestTemplateBypassingHostNameVerifcation() {
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
禁用 SSL 主机名验证器的完整代码,
RestTemplate restTemplate = new RestTemplate();
//to disable ssl hostname verifier
restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setHostnameVerifier(new NoopHostnameVerifier());
}
super.prepareConnection(connection, httpMethod);
}
});
要否决默认策略,您可以在连接 restTemplate 的类中创建一个简单的方法:
protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder
.create()
.setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
.build()));
}
注意:您当然需要处理异常,因为此方法只会进一步抛出异常!
这个问题是关于 SSL 连接的。当您尝试连接到某些资源时,https 协议需要创建安全连接。这意味着只有您的浏览器和网站服务器才知道请求正文中发送了哪些数据。这种安全性是通过存储在网站上并由您的浏览器(或任何其他客户端,在我们的例子中带有 Apache Http 客户端的 Spring RestTemplate)下载的 ssl 证书实现的,并首先连接到主机。有 RSA256 加密和许多其他很酷的东西。但最终:如果证书未注册或无效,您将看到证书错误(HTTPS 连接不安全)。要修复证书错误,网站提供商需要为特定网站购买它或以某种方式修复,例如https://www.register.com/ssl-certificates
如何解决问题的正确方法
如何解决问题不是正确的方法
将 SSL 证书导入 Java cacerts(证书存储)
keytool -importcert -trustcacerts -noprompt -storepass changeit -alias citrix -keystore "C:\Program Files\Java\jdk-11.0.2\lib\security\cacerts" -file citrix.cer
如何解决问题的肮脏(不安全)方式
使 RestTemplate 忽略 SSL 验证
@Bean
public RestTemplateBuilder restTemplateBuilder(@Autowired SSLContext sslContext) {
return new RestTemplateBuilder() {
@Override
public ClientHttpRequestFactory buildRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(
HttpClients.custom().setSSLSocketFactory(
new SSLConnectionSocketFactory(sslContext
, NoopHostnameVerifier.INSTANCE)).build());
}
};
}
@Bean
public SSLContext insecureSslContext() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
return SSLContexts.custom()
.loadTrustMaterial(null, (x509Certificates, s) -> true)
.build();
}
无需导入任何 APACHE 或 Any unknow 包的另一种方法非常简单。
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
private void ignoreCertificates() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
并在 RestTemplate 之前设置 ignoreCertificates():
ignoreCertificates();
RestTemplate restTemplate = new RestTemplate();
安全性:禁用 https/TLS 证书主机名检查,以下代码在 Spring Boot Rest 模板中工作
*HttpsURLConnection.setDefaultHostnameVerifier(
//SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// * @deprecated (4.4) Use {@link org.apache.http.conn.ssl.NoopHostnameVerifier}
new NoopHostnameVerifier()
);*
package com.example.teocodownloader;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class Example {
public static void main(String[] args) {
CloseableHttpClient httpClient
= HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory
= new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
}
}
顺便说一句,不要忘记在 pom 文件中添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
您还可以找到HttpClient<4.3 的 Java 代码示例。
如果您使用的是rest模板,您可以使用这段代码
fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
val timeout = envTimeout.toInt()
val config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build()
val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }
val sslContext: SSLContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build()
val csf = SSLConnectionSocketFactory(sslContext)
val client = HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.setSSLSocketFactory(csf)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build()
return HttpComponentsClientHttpRequestFactory(client)
}
@Bean
fun getRestTemplate(): RestTemplate {
return RestTemplate(getClientHttpRequestFactory())
}
@Bean
public RestTemplate restTemplate() throws Exception {
SSLContext sslContext = new SSLContextBuilder()
.loadKeyMaterial(keyStore, keyStorePassword.toCharArray(), keyStorePassword.toCharArray())
.loadTrustMaterial(trustStore, trustStorePassword.toCharArray(), (cert, authType) -> sslTrustStrategy)
.build();
HostnameVerifier hostnameVerifier = sslTrustStrategy ? new NoopHostnameVerifier() :
SSLConnectionSocketFactory.getDefaultHostnameVerifier();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
HttpComponentsClientHttpRequestFactory httpComponentsHttpClientFactory =
new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(httpComponentsHttpClientFactory);
return restTemplate;
}
如果 sslTrustStrategy = true,