我正在尝试从第三方服务器使用API。第三方向我发送了一个SSL认证名为certificate.p12,这是我用来进行握手的证书文件。我已经使用SSL创建了一个自定义RestTemplate,如下所示:
@Configuration
public class CustomRestTemplate {
private static final String PASSWORD = "fake_password";
private static final String RESOURCE_PATH = "keystore/certificate.p12";
private static final String KEY_TYPE = "PKCS12";
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {
char[] password = PASSWORD.toCharArray();
SSLContext sslContext = SSLContextBuilder
.create()
// .loadKeyMaterial(keyStore(RESOURCE_PATH, password), password)
.loadKeyMaterial(keyStore(getClass().getClassLoader().getResource(RESOURCE_PATH).getFile(), 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(KEY_TYPE);
File key = ResourceUtils.getFile(file);
try (InputStream in = new FileInputStream(key)) {
keyStore.load(in, password);
}
return keyStore;
}
}
然后我使用以下代码调用端点:
@Component
@Service
public class TransactionService implements TransactionInterface {
@Autowired
private CustomRestTemplate restTemplate = new CustomRestTemplate();
private static final String BASE_URL = "https://41.x.x.x:xxxx/";
@Override
public List<Transaction> getUnsentTransactions(int connectionId) throws Exception {
HttpEntity<?> httpEntity = new HttpEntity<>(null, new HttpHeaders());
ResponseEntity<Transaction[]> resp = restTemplate
.restTemplate(new RestTemplateBuilder())
.exchange(BASE_URL + "path/end_point/" + connectionId, HttpMethod.GET, httpEntity, Transaction[].class);
return Arrays.asList(resp.getBody());
}
}
在尝试使用api时,我得到以下stacktrace:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for \"https://41.x.x.x:xxxx/path/endpoint/parameters\": Certificate for <41.x.x.x> doesn't match any of the subject alternative names: [some_name_here, some_name_here];
我对TLS或SSL证书没有多少经验。我现在真的陷入困境,希望能在这里得到一些帮助。第三方为我提供了一个测试站点,我可以测试端点,在将certificate.p12文件导入浏览器后,我可以使用他们的测试站点到达端点,但我的Springboot应用程序仍然无法到达端点。
我是否需要将证书复制到特定文件夹中?这似乎不是这种情况,因为如果我更改路径或文件名,我得到一个FileNotFoundException,如果我输入了certificate.p12文件的错误密码,我会收到密码错误。我尝试使用Postman测试它,但Postman返回与我的Web应用程序相同的堆栈跟踪。
看看上面的信息,我错过了什么吗?是否在运行时期间未创建密钥库?我是否需要将证书绑定到JVM或我的传出请求?
任何帮助,将不胜感激。
谢谢
看起来您正在尝试连接到证书中没有有效名称的服务器。例如,如果要连接到“stackoverflow.com”,则证书需要“subject”或“subject alternative names”字段中的域。
即使是测试站点也应该有一个有效的证书,但如果这不可能(因为它是第三方站点而您自己无法更改),您可以使用this question禁用验证
当然,这只应该用于测试。