Spring Boot SSL Client

后端 未结 6 1750
抹茶落季
抹茶落季 2020-12-08 17:30

I am new to Spring Boot. So far I am enjoying it. I have developed a demo SSL rest web server that correctly handles mutual X.509 certificate authentication. Using an IE

6条回答
  •  孤街浪徒
    2020-12-08 17:58

    I know its too late, but here is the code that works for me.

    @SpringBootApplication
    public class Application {
    
    	private static final Logger log = LoggerFactory.getLogger(Application.class);
    
    	public static void main(String args[]) {
    
    			makeWebServiceCall();
    
    	}
    	
    	public static void makeWebServiceCall() {
    		TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    
    		SSLContext sslContext;
    		ResponseEntity response = null;
    		try {
    			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);
    			
    			StringBuffer plainCreds = new StringBuffer();
    			plainCreds.append("username");
    			plainCreds.append(":");
    			plainCreds.append("password");
    			byte[] plainCredsBytes = plainCreds.toString().getBytes();
    			byte[] base64CredsBytes = Base64.getEncoder().encode(plainCredsBytes);
    			String userBase64Credentials = new String(base64CredsBytes);
    			
    
    			HttpHeaders headers = new HttpHeaders();
    			headers.add("Authorization", "Basic " + userBase64Credentials);
    			headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    			headers.setContentType(MediaType.APPLICATION_JSON);
    
    			HttpEntity entity = new HttpEntity<>(headers);
    
    			String url = "https:restUrl";
    			
    			response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    			
    			if(response.getStatusCodeValue() == 200) {
    				log.info("Success! Further processing based on the need");
    			} else {
    				log.info("****************Status code received: " + response.getStatusCodeValue() + ".************************");
    			}
    
    		} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
    			log.error("Exception occured. Here are the exception details: ", e);
    		} catch(HttpClientErrorException e) {
    			if(e.getRawStatusCode() == 403) {
    				log.info("****************Status code received: " + e.getRawStatusCode() + ". You do not have access to the requested resource.************************");
    				
    			} else if(e.getRawStatusCode() == 404) {
    				log.info("****************Status code received: " + e.getRawStatusCode() + ". Resource does not exist(or) the service is not up.************************");
    
    			} else if(e.getRawStatusCode() == 400) {
    				log.info("****************Status code received: " + e.getRawStatusCode() + ". Bad Request.************************");
    
    			} else {
    				log.info("****************Status code received: " + e.getRawStatusCode() + ".************************");
    				
    			}
    
               log.info("****************Response body: " + e.getResponseBodyAsString() + "************************");
    		}
    	}
     }

    Here is the maven filed

    
    
    4.0.0
    
    org.springframework
    gs-consuming-rest
    0.1.0
    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.2.RELEASE
    
    
    
        1.8
    
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework
            spring-web
        
        
            com.fasterxml.jackson.core
            jackson-databind
        
    
    
    
        org.apache.httpcomponents
        httpclient
        4.5.3
    
    
    
            
    
        org.apache.httpcomponents
        httpcore
        4.4.6
    
    
    
    
    
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    
    

提交回复
热议问题