118

I'm trying to make a request with axios to an api endpoint and I'm getting the following error: Error: unable to verify the first certificate

It seems the https module, which axios uses, is unable to verify the SSL certificate used on the server.

When visiting the server with my browser, the certificate is valid and I can see/download it. I can also make requests to the api on my browser through https.

I can work around it by turning off verification. This code works.

const result = await axios.post(
    `https://${url}/login`,
    body,
    {
      httpsAgent: new https.Agent({
        rejectUnauthorized: false
      })
    }
  )

Problem is, this doesn't verify the SSL certificate and therefore opens up security holes.

How can I configure axios to trust the certificate and correctly verify it?

Jemi Salo
  • 3,401
  • 3
  • 14
  • 25
  • use native implementation of OkhttpClientFactory, https://stackoverflow.com/a/60116643/2685454 – Sumit Oct 05 '21 at 10:10
  • 1
    In case you are looking for posting using @nestjs/axios, refer this - https://stackoverflow.com/a/72588991/7102312 – iravinandan Jun 14 '22 at 01:07

9 Answers9

136

Old question but chiming in for those who land here. No expert. Please consult with your local security gurus and what not.

Axios is an http(s) client and http clients usually participate in TLS anonymously. In other words, the server accepts their connection without identifying who is trying to connect. This is different then say, Mutual TLS where both the server and client verify each other before completing the handshake.

The internet is a scary place and we want to protect our clients from connecting to spoofed public endpoints. We do this by ensuring our clients identify the server before sending any private data.

// DO NOT DO THIS IF SHARING PRIVATE DATA WITH SERVICE
const httpsAgent = new https.Agent({ rejectUnauthorized: false });

This is often posted (and more egregiously upvoted) as the answer on StackOverflow regarding https client connection failures in any language. And what's worse is that it usually works, unblocks the dev and they move on their merry way. However, while they certainly get in the door, whose door is it? Since they opted out of verifying the server's identity, their poor client has no way of knowing if the connection they just made to the company's intranet has bad actors listening on the line.

If the service has a public SSL cert, the https.Agent usually does not need to be configured further because your operating system provides a common set of publicly trusted CA certs. This is usually the same set of CA certs your browser is configured to use and is why a default axios client can hit https://google.com with little fuss.

If the service has a private SSL cert (self signed for testing purposes or one signed by your company's private CA to protect their internal secrets), the https agent must be configured to trust the private CA used to sign the server cert:

const httpsAgent = new https.Agent({ ca: MY_CA_BUNDLE });

where MY_CA_BUNDLE is an array of CA certs with both the server cert for the endpoint you want to hit and that cert's complete cert chain in .pem format. You must include all certs in the chain up to the trust root.


Where are these options documented?

HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module.

Therefore options passed to the https.Agent are a merge of the options passed to tls.connect() and tls.createSecureContext().

srquinn
  • 10,134
  • 2
  • 48
  • 54
  • 3
    This finally worked for me after I downloaded the cert and its chain. I had previously failed, because I only downloaded the certificate for the service I wanted to use. For anyone struggling like I was: make sure you download the whole chain as .pem. – Jemi Salo Dec 28 '18 at 09:04
  • 5
    @JemiSalo How to get whole chain of my self signed certificate? I solve id by doing like that: `const httpsAgent = new https.Agent({ ca: fs.readFileSync(certPath) });` – Suge May 28 '19 at 06:58
  • 3
    Where on Earth is this documented? I can't find any reference to a "ca" option in the docs for https.Agent. – user1974458 Jan 05 '21 at 11:15
  • @user1974458 Its super confusing, updated the answer with doc links for options – srquinn Mar 02 '21 at 21:41
  • I'm really confused here. Why is my browser able to trust a private CA, but axios running from a node script on the same machine is not?! – Magnus May 10 '21 at 15:28
  • @Magnus Both have to be configured to trust the private CA. You don't provide enough information about your environment to understand why your browser trusts the CA and your nodejs client does not. Post in another question and happy to help – srquinn May 12 '21 at 18:02
  • @srquinn Thanks for the offer -- here is the full question: https://stackoverflow.com/questions/67488917/how-to-get-axios-to-work-with-an-aws-acm-public-certificate – Magnus May 14 '21 at 18:00
  • I was having this issue as well, thanks to this answer and particularly the point where you mention that the whole certificate chain must be available, i was able to finally solve the problem. I had to use a Firefox on Ubuntu to download the PEM chain, it allows you to download either the certificate itself or the full chain, and I used the full chain and fed it in the HTTP agent request and lo and behold, it started to work – Edd Chang Jul 13 '22 at 08:41
  • This works fine in node js. what if I wanted to do the same in react native, or in client side. I already tried to use the native node modules in react native, but it did not work for dependency issues and no good docs about that. I am using expo. – Twfyq Bhyry Dec 20 '22 at 19:25
37

Create a custom agent with SSL certificate:

const httpsAgent = new https.Agent({
  rejectUnauthorized: false, // (NOTE: this will disable client verification)
  cert: fs.readFileSync("./usercert.pem"),
  key: fs.readFileSync("./key.pem"),
  passphrase: "YYY"
})

axios.get(url, { httpsAgent })

// or

const instance = axios.create({ httpsAgent })

From https://github.com/axios/axios/issues/284

Fabio Espinosa
  • 880
  • 6
  • 14
  • 12
    `rejectUnauthorized: false` disables client verification which is one of the OPs primary concerns. – srquinn Dec 02 '18 at 22:54
  • 1
    down voted as it's not wat the OP ask for. This answer, while still correct (except about `rejectUnauthorized`), is about client certificate, where OP want to verify server certificate – pomeh Sep 18 '19 at 14:17
  • Also I think the key parameter is a bit strange, what is that key of? – jambox Nov 20 '20 at 19:17
  • from where we can import https ?? in react native – Shafqat Bari Feb 07 '22 at 19:12
31

For me, when my application is running in development mode, I have disabled rejectUnauthorized directly in axios.defaults.options. This works very well. be careful and use this only in developer mode.

import https from 'https'
import axios from 'axios'
import config from '~/config'

/**
 * Axios default settings
 */
axios.defaults.baseURL = config.apiURL

/**
 * Disable only in development mode
 */
if (process.env.NODE_ENV === 'development') {
  const httpsAgent = new https.Agent({
    rejectUnauthorized: false,
  })
  axios.defaults.httpsAgent = httpsAgent
  // eslint-disable-next-line no-console
  console.log(process.env.NODE_ENV, `RejectUnauthorized is disabled.`)
}
Henrique Van Klaveren
  • 1,502
  • 14
  • 24
11

These configuration worked for me (In a Mutual Authentication scenario).

const httpsAgent = new https.Agent({
  ca: fs.readFileSync("./resource/bundle.crt"),        
  cert: fs.readFileSync("./resrouce/thirdparty.crt"),
  key: fs.readFileSync("./resource/key.pem"), 
})

Note: bundle.crt was prepared from provided certificates (root,intermediate,end entry certificate). Unfortunately no clear documentation found in this regards.

mnhmilu
  • 2,327
  • 1
  • 30
  • 50
  • 1
    to create a bundle just copy the contents of the certificates provided in reverse order into a text file. in `unix` the command would be in your case : `cat thirdparty.crt other.crt > bundle.crt` where the name of the bundle doesn't really matter. – rawplutonium Jun 11 '20 at 10:55
  • 1
    pleace tell me what is the other.crt? @rawplutonium – radiorz Nov 19 '21 at 03:11
8

This is very dirty, but at the top of your script, just put:

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

This basically tells node to not check SSL certificates, which is very convenient when you get self signed certificates rejected in development.

Please don't use this in production.

MetaZebre
  • 769
  • 8
  • 10
4

This worked for me:

import axios from 'axios'
import https from 'https'

const headers = {};

const httpsAgent = new https.Agent({
  ca: fs.readFileSync('./certs/cert.pem'),
  cert: fs.readFileSync('./certs/cert.pem'),
})

const data = await axios.get(url, { httpsAgent, headers })

EdwinN1337
  • 551
  • 5
  • 4
2

PS : Do not use this in production but just for debugging

This what worked for me, using axios with nodejs + express

exports.test_ssl = async (req,res) => { 
       
    let cert_file = fs.readFileSync("./ssl/my_self_signed_certificate.crt")
    let ca_file = fs.readFileSync("./ssl/my_self_signed_certificate_ca.crt")
    const agent = new https.Agent({
        requestCert: true,
        rejectUnauthorized: true, // not for production
        cert: cert_file,
        ca: ca_file
    });
    const options = {
        url: `https://example.com/test`,
        method: "POST",
        httpsAgent: agent,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/txt;charset=UTF-8'
        },
        data: {}
    };
    
    console.log(cert_file.toString())

    axios(options).then(response => {
        payload = response.data ;
        return res.status(200).send({"status":1});
    }).catch(err => {
        console.log(err);
        return false
    });

}
Nassim
  • 2,879
  • 2
  • 37
  • 39
  • 1
    This answer has `rejectUnauthorized: false` which turns off the identity check of the server and exposes your client to Man In the Middle attacks. See accepted answer, you should not be doing this in production workloads. – srquinn Feb 10 '22 at 15:58
1
const https = require('https');
const axios = require('axios')

const CA = "-----BEGIN CERTIFICATE-----$$$$$-----END CERTIFICATE-----"
const url = "bla"
const httpsAgent = new https.Agent({
  ca: CA
});

const response = await axios.get(url, { httpsAgent });

This is what work for me.

Tay-4
  • 81
  • 4
-1

Install https package

npm i https

create httpsAgent

const https = require('https');
    const httpsAgent = new https.Agent({
      rejectUnauthorized: false,
    });

pass this agent in axios call after url

const { data } = await axios.get(url, { httpsAgent });