java client authentication https connection (ignoring certificate validation and certificate validation in two ways)

First, according to the following operation generates a certificate, arranged springboot https, generate a simple https web service

https://www.cnblogs.com/qq931399960/p/11889349.html

Verify that the client pom-dependent

</dependency>
            <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.10</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.12</version>
            </dependency>

httpclient and httpcore version to correspond, otherwise exceptions may occur

Skip authentication methods including certificate authentication, that is, add trust, like when a self-signed https browser to access the service, the page will prompt you, click on Advanced, and continue to access the service that is added to the trust, another way it is to validate the server certificate, following directly on the code

Skip certificate authentication

package com.demo.bootdemo;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class SkipVerifyRestTemplateBuilder {

	private Logger logger = LoggerFactory.getLogger(SkipVerifyRestTemplateBuilder.class);

	// 初始化ssl resttemplate
	@Bean("skipVerifyRestTemplate")
	public RestTemplate skipVerifyRestTemplate() {
		RestTemplate rest = new RestTemplate();

		SSLConnectionSocketFactory buildSSLSocketFactory = null;
		try {
			buildSSLSocketFactory = this.buildSSLSocketFactory();
		} catch (Exception e) {
			logger.error("", e);
		}

		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
				HttpClients.custom().setSSLSocketFactory(buildSSLSocketFactory).build());

		factory.setConnectionRequestTimeout(1000);
		factory.setConnectTimeout(1000);
		
		rest.setRequestFactory(factory);
		return rest;
	}

	private SSLConnectionSocketFactory buildSSLSocketFactory() throws Exception {
		SSLContext sslContext = SSLContext.getInstance("SSL");
		// 设置信任证书(绕过TrustStore验证)
		sslContext.init(null, new TrustManager[] { new AuthX509TrustManager() }, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
				new String[] { "TLSv1" }, null, new HostnameVerifier() {
					// hostname,默认返回true,不验证hostname
					@Override
					public boolean verify(String urlHostName, SSLSession session) {
						return true;
					}
				});
		return sslConnectionSocketFactory;
	}

	private class AuthX509TrustManager implements TrustManager, X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkServerTrusted(X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
			return;
		}
	}
}

The second way to skip the certificate verification

package com.demo.bootdemo;

import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class SecondSkipVerifyRestTemplateBuilder {

    @Bean("secondSkipRestTemplate")
    public RestTemplate verifyCaRestTemplate() {
        RestTemplate rest = new RestTemplate();
        SSLConnectionSocketFactory ssLSocketFactory = null;
        try {
            ssLSocketFactory = sslFactory("PKCS12", "abc123");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                HttpClients.custom().setSSLSocketFactory(ssLSocketFactory).build());
        // 设置传递数据超时时长
        httpRequestFactory.setReadTimeout(1000);

        rest.setRequestFactory(httpRequestFactory);

        // 如果返回的数据非json则可能需要添加对应httpmessageconverter
        // Jaxb2RootElementHttpMessageConverter converter = new
        // Jaxb2RootElementHttpMessageConverter();
        //
        // List<MediaType> mediaTypeList = new ArrayList<>();
        // mediaTypeList.addAll(converter.getSupportedMediaTypes());
        // mediaTypeList.add(MediaType.TEXT_HTML);
        // converter.setSupportedMediaTypes(mediaTypeList);
        //
        // List<HttpMessageConverter<?>> list = new ArrayList<>();
        // list.add(converter);
        // rest.setMessageConverters(list);

        return rest;

    }

    public SSLConnectionSocketFactory sslFactory(String keyStoreType, String keyPassword) {
        SSLConnectionSocketFactory sslConnectionSocketFactory = null;
        try {
            SSLContext sslcontext = SSLContexts.custom()
                    // //忽略掉对服务器端证书的校验
                    .loadTrustMaterial(new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                            return true;
                        }
                    }).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslConnectionSocketFactory;
    }

}

According to the certificate validation

package com.demo.bootdemo;

import java.io.IOException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class VerifyCaRestTemplateBuilder {

    private Logger logger = LoggerFactory.getLogger(VerifyCaRestTemplateBuilder.class);

    @Value("classpath:cert.p12")
    private Resource certFile;

    @Bean("verifyCaRestTemplate")
    public RestTemplate verifyCaRestTemplate() {
        RestTemplate rest = new RestTemplate();

        SSLConnectionSocketFactory ssLSocketFactory = null;
        try {
            ssLSocketFactory = sslFactory("PKCS12", "abc123");
        } catch (Exception e) {
            logger.error("", e);
        }

        HttpComponentsClientHttpRequestFactory httpRequestFactory = newHttpComponentsClientHttpRequestFactory ( 
                . HttpClients.custom () setSSLSocketFactory (SSLSocketFactory) .build ()); 
        // set the data transfer timeout period 
        httpRequestFactory.setReadTimeout (1000 ); 

        rest.setRequestFactory (httpRequestFactory); 

        // if the data returned may be required non json adding the corresponding HttpMessageConverter
         // Jaxb2RootElementHttpMessageConverter Converter = new new
         // Jaxb2RootElementHttpMessageConverter ();
         // 
        // List <the MediaType> = new new mediaTypeList the ArrayList <> ();
         // mediaTypeList.addAll (converter.getSupportedMediaTypes ());
         // mediaTypeList.add (MediaType.TEXT_HTML);
        // converter.setSupportedMediaTypes(mediaTypeList);
        //
        // List<HttpMessageConverter<?>> list = new ArrayList<>();
        // list.add(converter);
        // rest.setMessageConverters(list);

        return rest;

    }

    public SSLConnectionSocketFactory sslFactory(String keyStoreType, String keyPassword) {
        SSLConnectionSocketFactory sslConnectionSocketFactory = null;
        try {
            KeyStore keyStore = null;
            try {
                keyStore =KeyStore.getInstance (keyStoreType); 
                keyStore.load (certFile.getInputStream (), keyPassword.toCharArray ()); 
            } the catch (IOException E) { 
                logger.error ( "" , E); 
            } 

            the HostnameVerifier HV = new new the HostnameVerifier () { 
                @override 
                public  boolean the verify (String urlHostName, SSLSession the session) {
                     // If you need to verify https domain, where the judge can do, if inconsistent access hostname and judgment, as an exception occurs
                     // IF ( "localhost" .equals (urlHostName)) {
                     // return to true;
                    // } the else {
                     // return to false;
                     // }
                     // here not check hostname, receive all hostname, just for testing. 
                    return  to true ; 
                } 
            }; 

            the SSLContext SSLContext = SSLContexts.custom () 
                    .loadTrustMaterial (certFile.getFile (), keyPassword.toCharArray (), new new TrustSelfSignedStrategy ()) 
                    .loadKeyMaterial (the keyStore, keyPassword.toCharArray ()) Build ().; 
            sslConnectionSocketFactory = new new SSLConnectionSocketFactory (SSLContext, new new String[] { "TLSv1" }, null, hv);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslConnectionSocketFactory;
    }

}

 

Test controller

package com.demo.bootdemo;

import javax.annotation.Resource;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
public class HttpsSendController {

    @Resource(name = "skipVerifyRestTemplate")
    private RestTemplate skipVerifyRestTemplate;

    @Resource(name = "verifyCaRestTemplate")
    private RestTemplate verifyCaRestTemplate;

    @Resource(name = "secondSkipRestTemplate")
    private RestTemplate secondSkipRestTemplate;

    @RequestMapping("/skip")
    @ResponseBody
    public String skipVerifyCert() {
        ResponseEntity<String> forEntity = skipVerifyRestTemplate.getForEntity("https://127.0.0.1:8443/test",
                String.class, new Object[] {});
        return forEntity.getBody();
    }

    @RequestMapping("/secondskip")
    @ResponseBody
    public String secondSkipVerifyCert() {
        ResponseEntity<String> forEntity = skipVerifyRestTemplate.getForEntity("https://127.0.0.1:8443/test",
                String.class, new Object[] {});
        return forEntity.getBody();
    }

    @RequestMapping("/verify")
    @ResponseBody
    public String verifyCert() {
        ResponseEntity<String> forEntity = verifyCaRestTemplate.getForEntity("https://127.0.0.1:8443/test",
                String.class, new Object[] {});
        returnforEntity.getBody (); 
    } 

}

Respectively, access to current clients skip, secondskip, verify verification results

 

Guess you like

Origin www.cnblogs.com/qq931399960/p/11904157.html