SpringBoot RestTemplate绕过HTTPS验证,亲测可用

废话不多说,具体没来得及研究,测试可用,暂时记录一下

声明:本系列所有文章皆属于测试案例,在虚构测试环境下进行测试,仅作为案例记录和技术分享。所有代码不涉及到敏感信息,严格遵守公司保密协议。

步骤非常简单

需要两个类,第一个是util工具类,另一个是restTemplate配置类
util类如下

package com.ieslab.utils;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @Author: zongshaofeng
 * @Description:
 * @Date:Create:in 2021/8/24 17:10
 * @Modified By:
 */
public class SSLUtil extends SimpleClientHttpRequestFactory {
	
	@Override
	protected void prepareConnection(HttpURLConnection connection, String httpMethod)
			throws IOException {
		if (connection instanceof HttpsURLConnection) {
			prepareHttpsConnection((HttpsURLConnection) connection);
		}
		super.prepareConnection(connection, httpMethod);
	}
	
	private void prepareHttpsConnection(HttpsURLConnection connection) {
		connection.setHostnameVerifier(new SkipHostnameVerifier());
		try {
			connection.setSSLSocketFactory(createSslSocketFactory());
		} catch (Exception ex) {
			// Ignore
		}
	}
	
	private SSLSocketFactory createSslSocketFactory() throws Exception {
		SSLContext context = SSLContext.getInstance("TLS");
		context.init(null, new TrustManager[]{new SkipX509TrustManager()},
				new SecureRandom());
		return context.getSocketFactory();
	}
	
	private class SkipHostnameVerifier implements HostnameVerifier {
		
		@Override
		public boolean verify(String s, SSLSession sslSession) {
			return true;
		}
		
	}
	
	private static class SkipX509TrustManager implements X509TrustManager {
		
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}
		
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}
		
		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}
		
	}
}

restTemplate配置类如下

package com.ieslab.config;

import com.ieslab.utils.SSLUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: zongshaofeng
 * @Description:
 * @Date:Create:in 2021/8/24 17:08
 * @Modified By:
 */
@Configuration
public class RestTemplateConfig {
	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
		return new RestTemplate(factory);
	}
	
	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
		SSLUtil factory = new SSLUtil();
		factory.setReadTimeout(3000);
		factory.setConnectTimeout(3000);
		return factory;
	}
}

剩下的工作就是按照正常的注入RestTemplate对象,然后使用restTemplate对象的getForEntity、getForObject等方法进行正常得到rest接口调用了。

最后说一下吧,我并没有来得及对这种绕过方式的原理进行深入了解,仅仅做过特定环境下的测试,可能不适合更加严格的安全环境,还需要根据自身情况进行测试,请知悉。

你可能感兴趣的:(开发百宝箱系列,https,java,resttemplate,spring)