developer tip

오류 : nodejs에서 첫 번째 인증서를 확인할 수 없습니다.

optionbox 2020. 8. 19. 07:58
반응형

오류 : nodejs에서 첫 번째 인증서를 확인할 수 없습니다.


URL을 사용하여 jira 서버에서 파일을 다운로드하려고하는데 오류가 발생합니다. 오류 를 확인하기 위해 코드에 인증서를 포함하는 방법 :

Error: unable to verify the first certificate in nodejs

at Error (native)
    at TLSSocket.<anonymous> (_tls_wrap.js:929:36)

  at TLSSocket.emit (events.js:104:17)

at TLSSocket._finishInit (_tls_wrap.js:460:8)

내 Nodejs 코드 :

var https = require("https");
var fs = require('fs');
var options = {
    host: 'jira.example.com',
    path: '/secure/attachment/206906/update.xlsx'
};

https.get(options, function (http_res) {

    var data = "";


    http_res.on("data", function (chunk) {

        data += chunk;
    });


    http_res.on("end", function () {

        var file = fs.createWriteStream("file.xlsx");
        data.pipe(file);

    });
});

적절한 루트 인증서를 추가해보십시오.

이것은 무단으로 승인되지 않은 엔드 포인트를 맹목적으로 받아들이는 것보다 항상 훨씬 더 안전한 옵션이 될 것이며, 이는 마지막 수단으로 만 사용해야합니다.

이것은 추가하는 것만 큼 간단 할 수 있습니다.

require('https').globalAgent.options.ca = require('ssl-root-cas/latest').create();

귀하의 응용 프로그램에.

SSL 루트 CA는 NPM 패키지 (로 여기에 사용)이 문제에 대한 매우 유용한 패키지입니다.


nodejs의 첫 번째 인증서를 확인할 수없는 경우 권한없는 거부가 필요합니다.

 request({method: "GET", 
        "rejectUnauthorized": false, 
        "url": url,
        "headers" : {"Content-Type": "application/json",
        function(err,data,body) {
    }).pipe(
       fs.createWriteStream('file.html'));

모든 요청을 안전하지 않게 만드는 또 다른 더러운 해킹 :

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0

The server you're trying to download from may be badly configured. Even if it works in your browser, it may not be including all the public certificates in the chain needed for a cache-empty client to verify.

I recommend checking the site in SSLlabs tool: https://www.ssllabs.com/ssltest/

Look for this error:

This server's certificate chain is incomplete.

And this:

Chain issues.........Incomplete


You may be able to do this by modifying the request options as below. If you are using a self-signed certificate or a missing intermediary, setting strictSSL to false will not force request package to validate the certificate.

var options = {
   host: 'jira.example.com',
   path: '/secure/attachment/206906/update.xlsx',
   strictSSL: false
}

GoDaddy SSL CCertificate

I've experienced this while trying to connect to our backend API server with GoDaddy certificate and here is the code that I used to solve the problem.

var rootCas = require('ssl-root-cas/latest').create();

rootCas
  .addFile(path.join(__dirname, '../config/ssl/gd_bundle-g2-g1.crt'))
  ;

// will work with all https requests will all libraries (i.e. request.js)
require('https').globalAgent.options.ca = rootCas;

PS:

Use the bundled certificate and don't forget to install the library npm install ssl-root-cas


This actually solved it for me, from https://www.npmjs.com/package/ssl-root-cas

// INCORRECT (but might still work)
var server https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii')
, cert: fs.readFileSync('cert.pem', 'ascii')   // a PEM containing ONLY the SERVER certificate
});

// CORRECT (should always work)
var server https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii')
, cert: fs.readFileSync('fullchain.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
});

This Worked For me => adding agent and 'rejectUnauthorized' set to false

const https = require('https'); //Add This
const bindingGridData = async () => {
  const url = `your URL-Here`;
  const request = new Request(url, {
    method: 'GET',
    headers: new Headers({
      Authorization: `Your Token If Any`,
      'Content-Type': 'application/json',
    }),
    //Add The Below
    agent: new https.Agent({
      rejectUnauthorized: false,
    }),
  });
  return await fetch(request)
    .then((response: any) => {
      return response.json();
    })
    .then((response: any) => {
      console.log('response is', response);
      return response;
    })
    .catch((err: any) => {
      console.log('This is Error', err);
      return;
    });
};


I was using nodemailer npm module. The below code solved the issue

     tls: {
     // do not fail on invalid certs
     rejectUnauthorized: false
     }

참고URL : https://stackoverflow.com/questions/31673587/error-unable-to-verify-the-first-certificate-in-nodejs

반응형