微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用springtemplate在春天发出的每个请求发送客户端证书的正确方法是什么?

我想用我的spring应用程序使用REST服务.要访问该服务,我有一个客户端证书(自签名和.jks格式)进行授权.
对其他服务进行身份验证的正确方法是什么?

这是我的要求:

public ListSyntaxException {

    httpentityhttpentity = new httpentity<>(null,new HttpHeaders());

    ResponseEntityhttpentity,Info[].class);
    return Arrays.asList(resp.getBody());
}
最佳答案
以下是使用RestTemplateApache 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 ListSyntaxException {
    httpentityhttpentity = new httpentity<>(null,new HttpHeaders());

    ResponseEntity

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐