3

So I am calling an API that requires me to have a pfx certificate linked either to my browser or to Postman if I am calling that API. I want to do this programmatically. If there is a code in R that let's me use my existing pfx certificate while passing the post request or a function that I can use to convert my existing pfx certificate to pem certificate. Kindly help me in solving the issue.

Phil
  • 7,287
  • 3
  • 36
  • 66
Mave
  • 31
  • 1

2 Answers2

0

I had the same problem and solved it this way:

library(openssl)
library(httr)
library(usethis)

# set up openssl in .Renviron
usethis::edit_r_environ() #opens .Renviron file in Rstudio
# include this line into .Renviron file:
CURL_SSL_BACKEND="openssl"

# read your pfx certificate 
cert <- openssl::read_p12(file = ".../yourCertificate.pfx", password = "yourKey")

# convert pfx to cert and key pem files to use in httr calls
openssl::write_pem(cert$cert, "my_cert.pem")
openssl::write_pem(cert$key, "my_key.pem")

# send request
GET("https://...", config = config(sslcert =  "my_cert.pem", sslkey = "my_key.pem"), verbose())
NinaO
  • 1
  • 1
0

As of April 2023 the get method returns an error:

schannel: Failed to import cert file my_cert.pem, last error is 0x80092002

This seems to be linked to the issue introduced in curl in 7.55.1 (see https://stackoverflow.com/a/71496170/5956120) In curl 8.0.1 using the certificate works again.

A workaround could be implemented in R:

# request via external tool curl (https://curl.se/windows/)
responseText <- system("<pathToCurl>/curl-8.0.1_6-win64-mingw/bin/curl.exe --cert my_cert.pem --key my_key.pem https://... -sS", intern = TRUE)
responseJson <- paste(responseText, collapse = '')