How do you include an SSL certificate in an API request in Node?
Asked Answered
T

0

8

Here is the situation: I have a certificate, key, public key, and private key. I am building an app that integrates with another system. My system is a Next.js app running on Azure. It makes API requests to an external server running somewhere else. I know that my certificate/keys are good because the request works when I use the Insomnia API Client (200 response and data coming back).

However, trying to do this in Node, I keep getting 400 errors. I have tried doing this with core fetch and https functionalities and using the node-fetch package. I also looked at the request package (as there are examples of this on the internet), but that package was deprecated over a year ago, so I think it should not be used.

Here's an example of some of the code I've tried using. I'm storing the certs/keys in /tmp/certs on my local system & they are loading (I've been logging heavily). I've used a wide variety of different requestOptions, but nothing seems to be doing the trick.

import fs from 'fs'
import fetch from 'node-fetch'

const requestOptions = {
    method: 'GET',
    port: 443,
    cert: fs.readFileSync("/tmp/certs/ct.crt", 'utf-8'),
    key: fs.readFileSync("/tmp/certs/ct.key", 'utf-8')
  };

const res = await fetch("https://url.com?unique_ID=1234&key=abcd", requestOptions);

Examining the res always turns up a 400. I have tried doing this a number of different ways at this point. This seems like it should be a trivial, common use case... What am I doing wrong and how should I be structuring this request?

Help me, Stack Overflow, you're my only hope!

Tegument answered 14/5, 2021 at 1:20 Comment(1)
You need to use a custom agent. See sebtrif.xyz/blog/… on how to do it.Lowrie

© 2022 - 2024 — McMap. All rights reserved.