복붙노트

[SPRING] 봄에 resttemplate이 요청할 때마다 클라이언트 인증서를 보내는 올바른 방법은 무엇입니까?

SPRING

봄에 resttemplate이 요청할 때마다 클라이언트 인증서를 보내는 올바른 방법은 무엇입니까?

내 봄 응용 프로그램과 함께 REST 서비스를 사용하려고합니다. 해당 서비스에 액세스하려면 인증을 위해 클라이언트 인증서 (자체 서명 및 .jks 형식)가 있어야합니다. 나머지 서비스에 대해 인증하는 적절한 방법은 무엇입니까?

이것은 나의 요청이다.

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());
}

해결법

  1. ==============================

    1.RestTemplate 및 Apache HttpClient를 사용하여이를 수행하는 방법을 보여주는 예제가 있습니다.

    RestTemplate 및 Apache HttpClient를 사용하여이를 수행하는 방법을 보여주는 예제가 있습니다.

    SSL 컨텍스트가 구성된 자체 RestTemplate을 정의해야합니다.

    @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를 클래스 경로에 넣어야합니다.

    @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());
    }
    
  2. ==============================

    2.또는 인증서를 JDK cacerts로 가져올 수 있으며 jdk (귀하의 경우에는 나머지 템플리트)를 사용하는 모든 HTTP 클라이언트가 인증서를 사용하여 REST 호출을 작성합니다.

    또는 인증서를 JDK cacerts로 가져올 수 있으며 jdk (귀하의 경우에는 나머지 템플리트)를 사용하는 모든 HTTP 클라이언트가 인증서를 사용하여 REST 호출을 작성합니다.

    keytool -import -keystore $JAVA_HOME/jre/lib/security/cacerts -file foo.cer -alias alias
    

    추신 : 성공적인 가져 오기 후에 서버를 다시 시작하는 것을 잊지 마십시오. 키 저장소의 기본 암호 - changeit

  3. from https://stackoverflow.com/questions/45713593/what-is-the-right-way-to-send-a-client-certificate-with-every-request-made-by-th by cc-by-sa and MIT license