How to do HTTPS GET with client certificate in Axios

rok picture rok · Aug 26, 2018 · Viewed 7.3k times · Source

How to perform get request with client certificate like below using chai-http?

curl -k --key [key_path] --cert [cert-path]:secret 'https://127.0.0.1/url'

The following code returns error:

Error: error:0906A068:PEM routines:PEM_do_header:bad password read

I guess it's because of missing passphrase argument.

let chai = require('chai');
let chaiHttp = require('chai-http');

let should = chai.should();
var expect = chai.expect;

chai.use(chaiHttp);

// load certificates
let fs = require('fs')
let key = fs.readFileSync(__dirname + '/user.key')
let cert = fs.readFileSync(__dirname + '/user.crt')

describe('client certificate call', () => {
    it('should return data', () => {
        chai.request('https://127.0.0.1')
        .get('/url')
        .key(key)
        .cert(cert, 'secret')
        // .passphrase('secret')
        .end((err, res) => {
                res.should.have.status(200);
                done();
            });
        });

})

Using axios did the trick:

var axios = require('axios')
var https = require('https')
var fs = require('fs')

var instance = axios.create({

    httpsAgent: new https.Agent({
        cert: fs.readFileSync(`user.cert`),
        key: fs.readFileSync(`user.key`),
        passphrase: 'secret',
        rejectUnauthorized: false
    })
})

instance.get('url')
        .then( function(response) {
        console.log(response)
    })

Answer