代码之家  ›  专栏  ›  技术社区  ›  Nas3nmann

在spring中,通过resttemplate发出的每个请求发送客户端证书的正确方法是什么?

  •  23
  • Nas3nmann  · 技术社区  · 7 年前

    我想在spring应用程序中使用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());
    }
    
    2 回复  |  直到 7 年前
        1
  •  41
  •   Ruslan Poshuk    7 年前

    下面是如何使用 RestTemplate Apache 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 :您需要 证书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
  •   Abhijeet Ahuja    6 年前

    或者,您可以将证书导入JDKs cacerts,所有使用jdk的HTTP客户端(在您的情况下是rest模板)都将使用证书进行rest调用。

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

    P、 S:不要忘记在成功导入后重新启动服务器。密钥库的默认密码- changeit