Skip to content

Instantly share code, notes, and snippets.

@harssh
Created August 30, 2023 13:55
Show Gist options
  • Save harssh/f24f623b1db3770e3a40c789c975e442 to your computer and use it in GitHub Desktop.
Save harssh/f24f623b1db3770e3a40c789c975e442 to your computer and use it in GitHub Desktop.
Add certificate and key in Rust API request
//https://www.reddit.com/r/learnrust/comments/y5qm0y/certificates_in_reqwest_crate/
let mut headers = HeaderMap::new();
headers.insert(ACCEPT, "application/json".parse().unwrap());
headers.insert("X-Application", "someKey".parse().unwrap());
// Format body
let login_params = [("username", "myusername"), ("password", "password")];
// create a certificate identity
let mut buf = Vec::new();
File::open("client-2048.crt")?.read_to_end(&mut buf)?;
File::open("client-2048.key")?.read_to_end(&mut buf)?;
let id = reqwest::Identity::from_pem(&buf)?;
let client = reqwest::Client::builder()
.use_rustls_tls()
.identity(id)
.build()?;
let res = client
.post("https://someurl.com/api/certlogin")
.headers(headers)
.form(&login_params)
.send()
.await?
.json::<serde_json::Value>()
.await?;