2

我想用我的spring應用程序來使用REST服務。要訪問該服務我有一個客戶端證書(自簽名和.jks格式)授權。 什麼是對其他服務進行身份驗證的正確方法?在spring中每個請求都發送一個客戶端證書的正確方法是什麼?

這是我的要求:

public List<Info> getInfo() throws RestClientException, URISyntaxException { 

    HttpEntity<?> httpEntity = new HttpEntity<>(null, new HttpHeaders()); 

    ResponseEntity<Info[]> resp = restOperations.exchange(
      new URI(BASE_URL + "/Info"), HttpMethod.GET, 
      httpEntity, Info[].class); 
    return Arrays.asList(resp.getBody()); 
} 

回答

4

下面是例子,如何做到這一點使用RestTemplateApache HttpClient

你應該定義自己的RestTemplate與配置SSL上下文:

@Bean 
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception { 
    char[] password = "password".toCharArray(); 

    SSLContext sslContext = SSLContextBuilder.create() 
      .loadKeyMaterial(keyStore("classpath:cert.jks", password), password) 
      .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); 

    HttpClient client = HttpClients.custom().setSSLContext(sslContext).build(); 
    return builder 
      .requestFactory(new HttpComponentsClientHttpRequestFactory(client)) 
      .build(); 
} 

private KeyStore keyStore(String file, char[] password) throws Exception { 
    KeyStore keyStore = KeyStore.getInstance("PKCS12"); 
    File key = ResourceUtils.getFile(file); 
    try (InputStream in = new FileInputStream(key)) { 
     keyStore.load(in, password); 
    } 
    return keyStore; 
} 

現在此模板執行的所有遠程呼叫都將使用cert.jks進行簽名。 注意:你會需要把cert.jks到你的classpath

@Autowired 
private RestTemplate restTemplate; 

public List<Info> getInfo() throws RestClientException, URISyntaxException { 
    HttpEntity<?> httpEntity = new HttpEntity<>(null, new HttpHeaders()); 

    ResponseEntity<Info[]> resp = restTemplate.exchange(
      new URI(BASE_URL + "/Info"), HttpMethod.GET, 
      httpEntity, Info[].class); 
    return Arrays.asList(resp.getBody()); 
} 
+0

的偉大工程的感謝! – Nas3nmann

相關問題