From this source: RESTAssured - use.pfx certificate for https call I created below.
@Test
void testPfxKey() {
// Source: https://stackoverflow.com/questions/42235588/restassured-use-pfx-certificate-for-https-call
FileInputStream instream1=null;
KeyStore keyStore=null;
org.apache.http.conn.ssl.SSLSocketFactory lSchemeSocketFactory=null;
try {
instream1 = new FileInputStream(new File("C:/Path/To/pfxfile.pfx"));
keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(instream1, "pfxfilepwd".toCharArray());
X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
lSchemeSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, "pfxfilepwd");
lSchemeSocketFactory.setHostnameVerifier(hostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
RestAssured.config = RestAssured.config().sslConfig(new SSLConfig().with().sslSocketFactory(lSchemeSocketFactory).and().allowAllHostnames().relaxedHTTPSValidation());
RestAssured.given().
contentType("application/json").
headers(
"Subscription-Key", "key-value",
"Accept-Encoding", "gzip,deflate"
);
Response response = RestAssured.get("https://endpoint.net/resource/path");
System.out.println(response.getStatusCode());
}
response.getStatusCode() always returns 401. I am expecting a 200. I have checked keyfile path, password and also the enpoint. All seem to be OK. When I run use ReadyAPI then I get a response. Please advice how to resolve this issue. Thanks you all!
I found this issue. I need to send headers with each request. Also.relaxedHTTPSValidation() should NOT be used in this case: We are in fact providing certificates that should be authenticated! Below code works:
@Test
void testPfxKey() {
FileInputStream instream1 = null;
KeyStore keyStore = null;
org.apache.http.conn.ssl.SSLSocketFactory lSchemeSocketFactory = null;
try {
instream1 = new FileInputStream(new File("C:/Path/To/pfxfile.pfx"));
keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(instream1, "pfxfilepwd".toCharArray());
X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
lSchemeSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, "pfxfilepwd");
lSchemeSocketFactory.setHostnameVerifier(hostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
RestAssured.config = RestAssured.config().sslConfig(new SSLConfig().with().sslSocketFactory(lSchemeSocketFactory).and().allowAllHostnames());
System.out.println(
RestAssured.given().
contentType("application/json").
headers(
"Subscription-Key", "key-value",
"Accept-Encoding", "gzip,deflate"
)
.get("https://endpoint.net/resource/path")
.getStatusCode()
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.