In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use RestTemplate to call the https interface to skip certificate verification. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
RestTemplate calls https API to skip certificate verification import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager; import java.nio.charset.StandardCharsets;import java.security.cert.CertificateException; import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.springframework.http.client.HttpComponentsClientHttpRequestFactory Import org.springframework.http.converter.StringHttpMessageConverter;import org.springframework.web.client.RestTemplate; public class NoHttpsClientUtils {/ * skip sslcontext * * @ return * @ throws Exception * / private static SSLContext createIgnoreVerifySSL () throws Exception {SSLContext sc = SSLContext.getInstance ("TLS") / / implement a X509TrustManager interface to bypass verification There is no need to modify the method X509TrustManager trustManager = new X509TrustManager () {@ Override public void checkClientTrusted (java.security.cert.X509Certificate [] paramArrayOfX509Certificate, String paramString) throws CertificateException {} @ Override public void checkServerTrusted (java.security.cert.X509Certificate [] paramArrayOfX509Certificate) String paramString) throws CertificateException {} @ Override public java.security.cert.X509Certificate [] getAcceptedIssuers () {return null }}; sc.init (null, new TrustManager [] {trustManager}, null); return sc;} / * construct RestTemplate * * @ return * @ throws Exception * / public static RestTemplate getRestTemplate () throws Exception {HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory (); / / timeout factory.setConnectionRequestTimeout (5000) Factory.setConnectTimeout (5000); factory.setReadTimeout (5000) SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory (createIgnoreVerifySSL (), / / specify TLS version null, / / specify algorithm null, / / cancel domain name verification new HostnameVerifier () {@ Override public boolean verify (String string) SSLSession ssls) {return true }}); CloseableHttpClient httpClient = HttpClients.custom (). SetSSLSocketFactory (sslsf). Build (); factory.setHttpClient (httpClient); RestTemplate restTemplate = new RestTemplate (factory); / / solve the problem of Chinese garbled restTemplate.getMessageConverters (). Set (1, new StringHttpMessageConverter (StandardCharsets.UTF_8)); return restTemplate;}} RestTemplate encountered SSL certificate verification error when accessing https
Today, I encountered a problem of SSL certificate authentication, which took a long time to solve. I learned a lot, recorded it and shared it with you.
First of all, to talk about the general background, our project docks with a third-party interface and needs to send a https request to the other party. Then the problem arises. When you make a https request, you need to be authenticated by SSL certificate. Today, the process suddenly fails. If you look at the log, it is found that it is the problem of SSL authentication:
There are two ways to solve the problem by looking for information on the Internet:
1. Through the relevant configuration, skip SSL certificate verification and complete the request.
two。 Download the certificate and import it into the certificate management of JDK.
The first method is equivalent to trick, evade the problem, of course we can not do that, we have to meet the challenge, so the editor directly pass the first, choose the second.
Add Https certificate download certificate
First, save the unsigned certificate locally through the browser, and the specific steps are as follows:
Click insecure-> Certificate-> details-> copy to a file, then select a file name by default and save it.
(Mac download: Mac cannot find the copy button. Just click the lock on the address bar, click the certificate, and then drag the blue file to the folder you want to download. It's best to rename it for easy to use.
Import certificate
We need to import the certificate into the certificate management of JDK to use the certificate we just downloaded in the project. The import commands are as follows:
Keytool-import-noprompt-trustcacerts-alias-keystore / Users/ZHONGHUI/develop/jdk-12.0.2.jdk/Contents/Home/lib/security/cacerts-storepass changeit-file eleme.cer
Among them, because we use JDK12, which is different from the commonly used JDK8 directory, so my cacerts directory is: / Users/ZHONGHUI/develop/jdk-12.0.2.jdk/Contents/Home/lib/security/cacerts, if you are using JDK1.8 or 1.7, then your cacerts is under / lib/security/ under jre. Eleme is the alias we got for the copied certificate, and eleme.cer is the certificate we downloaded and renamed. Changeit is the password. If changeit doesn't work, try changeme, usually changeit.
Generate keystore file keytool-import-storepass changeit-file eleme.cer-keystore eleme.keystore
Then an eleme.keystore file will be generated, and if you don't have enough permissions, just add sudo. Copy it to the classpath of the project.
Configuration in the project
Replace the following RestTemplateConfig with the original:
Package com..xxx.config; import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.security.KeyManagementException;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List; import org.apache.http.config.Registry;import org.apache.http.config.RegistryBuilder;import org.apache.http.conn.socket.ConnectionSocketFactory;import org.apache.http.conn.socket.PlainConnectionSocketFactory Import org.apache.http.conn.ssl.NoopHostnameVerifier;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.ssl.SSLContextBuilder;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource Import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;import org.springframework.web.client.RestTemplate; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; @ Configurationpublic class RestTemplateConfig {@ Autowired private FastJsonHttpMessageConverter httpMessageConverter @ Bean RestTemplate restTemplate () throws Exception {HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory (); factory.setConnectionRequestTimeout (5 * 60 * 1000); factory.setConnectTimeout (5 * 60 * 1000); factory.setReadTimeout (5 * 60 * 1000) / / https SSLContextBuilder builder = new SSLContextBuilder (); KeyStore keyStore = KeyStore.getInstance (KeyStore.getDefaultType ()); ClassPathResource resource = new ClassPathResource ("nonghang.keystore"); InputStream inputStream = resource.getInputStream (); keyStore.load (inputStream, null); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory (builder.build (), NoopHostnameVerifier.INSTANCE) Registry registry = RegistryBuilder.create () .register ("http", new PlainConnectionSocketFactory ()) .register ("https", socketFactory) .build (); PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager (registry); phccm.setMaxTotal CloseableHttpClient httpClient = HttpClients.custom (). SetSSLSocketFactory (socketFactory) .setConnectionManager (phccm) .setConnectionManagerShared (true). Build (); factory.setHttpClient (httpClient); RestTemplate restTemplate = new RestTemplate (factory); List > convertersValid = new ArrayList () For (HttpMessageConverter converter: converters) {if (converter instanceof MappingJackson2HttpMessageConverter | | converter instanceof MappingJackson2XmlHttpMessageConverter) {continue;} convertersValid.add (converter);} convertersValid.add (httpMessageConverter); restTemplate.setMessageConverters (convertersValid); inputStream.close () Return restTemplate;}}
Well, everything is ready except Dongfeng. I tried it confidently and found that it still didn't work. I was deeply shocked and decided to take a look at the causes of this kind of error.
From the root, how does https's socket work?
The flow chart of https's socket operation is as follows:
So, what is a SSL certificate?
SSL certificate complies with SSL protocol and is issued by CA, a trusted digital certificate authority, after verifying the identity of the server. It has the functions of server authentication and data transmission encryption.
First of all, it is important to know that the reason for reporting this exception is not just because the certificate verification failed.
1. When we link to the server through https, the server will return a certificate to us, which may be verified by CA or unauthenticated homemade certificate. After getting this certificate, the client will verify the certificate. If it is a certificate verified by CA, the natural certificate verification will pass, and the self-made certificate will naturally be verified differently, resulting in the above exception.
two。 After the certificate verification is passed, you also need to verify whether the accessed domain name matches the domain name specified by the certificate. A mismatch can also cause the above exception.
3. The handshake begins only after the above two steps have been verified, but the handshake may also fail, resulting in the above exception.
This is the end of the article on "how to use RestTemplate to call https interface to skip certificate verification". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.