Making a REST call in Node.js that requires client certificate for authentication
Asked Answered
F

1

13

Is there a way to make a rest call that requires a client certificate for authentication through Node.js ?

Foible answered 10/5, 2014 at 6:48 Comment(0)
C
19

Yes, you can do that quite simply, here done using a regular https request;

var https = require('https'),                  // Module for https
    fs =    require('fs');                     // Required to read certs and keys

var options = {
    key:   fs.readFileSync('ssl/client.key'),  // Secret client key
    cert:  fs.readFileSync('ssl/client.crt'),  // Public client key
    // rejectUnauthorized: false,              // Used for self signed server
    host: "rest.localhost",                    // Server hostname
    port: 8443                                 // Server port
};

callback = function(response) {
  var str = '';    
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

https.request(options, callback).end();
Candent answered 10/5, 2014 at 7:33 Comment(3)
How do i pass a JSON or XML in the request body if i use this approach ?Foible
@AnandDivakaran If you need the full code for a post request, this answer shows how to do that. In this case, you'll only need to replace http with https and add the key and cert options shown above to the post_options for client certificates to work.Candent
Isn't there a library which handles client-side certificates? I was using node-rest-client but ran into this need and it doesn't seem to support that.Controller

© 2022 - 2024 — McMap. All rights reserved.