基于上一篇文章生成的证书:Nginx-配置HTTPS证书(单向认证)_孟孟的博客-CSDN博客_nginx配置https访问
一、证书转换
- 服务方给的证书多为"cer"类型,比如直接从浏览器中下载下来的,该类证书不能直接使用java调用认证,需转换为java可识别的类型,比如".keystore"。
- 利用jdk中"keytool"命令进行转换,即证书导入,执行命令:
keytool -importcert -keystore client.keystore -file nginx.crt
?
二、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
三、配置RestTemplate
RestTemplate包含以下几个部分:
- HttpMessageConverter 对象转换器:将请求对象转换为具体的数据格式输出,例
入:Jaxb2RootElementHttpMessageConverterket提供对xml格式的输入输出支持 - ClientHttpRequestFactory HTTP请求工厂,默认是JDK的HttpURLConnection,
可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式 - ResponseErrorHandler 异常错误处理
- ClientHttpRequestInterceptor 请求拦截器
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.security.KeyStore;
/**
* RestTemplate - https证书认证
*/
@Configuration
public class RestTemplateOfCerConfig {
//证书路径
@Value("${client.keystore}")
private String cerPath;
//使用"keytool"命令导入证书时输入的密码
@Value("${client.password}")
private String cerPwd;
@Bean(name = "sslRestTemplate")
public RestTemplate gkRestTemplate() throws Exception {
RestTemplate restTemplate = null;
//https协议证书认证
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(ResourceUtils.getFile(cerPath)), cerPwd.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build();
// 这里的通信协议要根据使用的JDK版本来适配
SSLConnectionSocketFactory sslfactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null,
NoopHostnameVerifier.INSTANCE);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.setSSLSocketFactory(sslfactory).build();
HttpComponentsClientHttpRequestFactory httpsFactory = new HttpComponentsClientHttpRequestFactory(closeableHttpClient);
httpsFactory.setReadTimeout(2000);
httpsFactory.setConnectTimeout(2000);
restTemplate = new RestTemplate(httpsFactory);
return restTemplate;
}
}
PS:Java 8将默认使用传输级别安全性TLSv1.2
四、使用sslRestTemplate
在service层使用sslRestTemplate
@Resource(name = "sslRestTemplate")
private RestTemplate sslRestTemplate;
|