Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AxiosError: self signed certificate #5407

Open
meate-onlines opened this issue Dec 26, 2022 · 10 comments
Open

AxiosError: self signed certificate #5407

meate-onlines opened this issue Dec 26, 2022 · 10 comments

Comments

@meate-onlines
Copy link

Describe the bug

AxiosError: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1507:34)
at TLSSocket.emit (events.js:376:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 100000,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, /',
'Cache-Control': 'no-cache',
dataSource: 'guangdong',
'Content-Type': 'application/json',
'User-Agent': 'axios/0.27.2',
'Content-Length': 2
},
retry: 0,
retryDelay: 500,
url: 'https://gd-school-front-test-tmp.kukewang.com/test-api/client/major/tree',
method: 'get',
data: '{}',
params: {}
},
request: <ref *1> Writable {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: null,
closed: false
},
_events: [Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError],
socket: [Array]
},
_eventsCount: 3,
_maxListeners: undefined,
_options: {
maxRedirects: 21,
maxBodyLength: 10485760,
protocol: 'https:',
path: '/test-api/client/major/tree',
method: 'GET',
headers: [Object],
agent: undefined,
agents: [Object],
auth: undefined,
hostname: 'gd-school-front-test-tmp.kukewang.com',
port: null,
nativeProtocols: [Object],
pathname: '/test-api/client/major/tree'
},
_ended: false,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 2,
_requestBodyBuffers: [ [Object] ],
_onNativeResponse: [Function (anonymous)],
_currentRequest: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: true,
socket: [TLSSocket],
_header: 'GET /test-api/client/major/tree HTTP/1.1\r\n' +
'Accept: application/json, text/plain, /\r\n' +
'Cache-Control: no-cache\r\n' +
'dataSource: guangdong\r\n' +
'Content-Type: application/json\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Content-Length: 2\r\n' +
'Host: gd-school-front-test-tmp.kukewang.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/test-api/client/major/tree',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'gd-school-front-test-tmp.kukewang.com',
protocol: 'https:',
_redirectable: [Circular *1],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
_currentUrl: 'https://gd-school-front-test-tmp.kukewang.com/test-api/client/major/tree',
_timeout: null,
[Symbol(kCapture)]: false
}
}

To Reproduce

No response

Code snippet

No response

Expected behavior

No response

Axios Version

No response

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

No response

OS

No response

Additional Library Versions

No response

Additional context/Screenshots

No response

@Rashed-MM
Copy link

One possible solution is to disable certificate validation by setting the rejectUnauthorized option to false in the Axios configuration. However, this is generally not recommended, as it can weaken the security of your application. A better option would be to obtain a valid certificate from a trusted CA and configure your server to use it.

Alternatively, if you are unable to obtain a valid certificate and need to make a request to a server with a self-signed certificate, you can add the certificate to your application's trusted certificate store. This will allow your application to trust the self-signed certificate and make requests to the server without encountering this error.

It's also possible that the certificate being presented by the server is not the correct certificate for the hostname being accessed. In this case, you may need to check the server's configuration to ensure that the correct certificate is being used.

@fullflash
Copy link

rejectUnauthorized not working on latest axios version 1.2.2

with code CERT_HAS_EXPIRED
Error: certificate has expired
    at AxiosError.from (node_modules/axios/dist/node/axios.cjs:789:14)
    at RedirectableRequest.handleRequestError (/axios/dist/node/axios.cjs:2744:25)
    at RedirectableRequest.emit (node:events:525:35)
    at eventHandlers.<computed> (//follow-redirects/index.js:14:24)
    at ClientRequest.emit (node:events:513:28)
    at TLSSocket.socketErrorListener (node:_http_client:490:9)
    at TLSSocket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

@Rashed-MM
Copy link

You mentioned that you are using the latest version of Axios (version 1.2.2) and that the rejectUnauthorized option is not working. One possible reason for this is that the rejectUnauthorized option has been removed in Axios version 1.2.0 and later. This option was used to control whether to reject connections with invalid or expired SSL/TLS certificates, but it was removed due to security concerns.

Instead of using the rejectUnauthorized option, you can use the validateStatus option to control whether to reject a response based on the HTTP status code. For example, you could set validateStatus to a function that returns true for status codes in the 2xx range (success) and false for all other status codes (failure).

Alternatively, you can use the https.checkServerIdentity option to customize the certificate verification process. This option should be set to a function that takes in the server's hostname and certificate and returns an error if the certificate is invalid or otherwise should not be trusted.

Here is an example of how you could use the validateStatus and https.checkServerIdentity options to customize the certificate verification process in Axios:


const axios = require('axios');

const instance = axios.create({
  https: {
    checkServerIdentity: (host, cert) => {
      // Customize certificate verification here, returning an error if the
      // certificate is invalid or should not be trusted.
    }
  },
  validateStatus: status => {
    // Only reject responses with status codes outside the 2xx range
    return status >= 200 && status < 300;
  }
});

instance.get('https://example.com')
  .then(response => {
    // Handle success
  })
  .catch(error => {
    // Handle error
  });

@pindab0ter
Copy link

The checkServerIdentity is not called if it's a DEPTH_ZERO_SELF_SIGNED_CERT error. Do you know of any way to validate using checkServerIdentity regardless?

@EtienneT
Copy link

Any workaround for this?

Thanks,

@pindab0ter
Copy link

pindab0ter commented Apr 20, 2023

The workaround I ended up using is to manually implement trust on first use.

Practically:

  1. Get the certificate using tls.connect using rejectUnauthorized: false and getPeerCertificate in the callback.
  2. Make a PEM certificate string out of the peerCertificate.raw buffer.
  3. Send that along as the ca option in any subsequent requests.

Example:
pindab0ter/raycast-hue:src/helpers/hueNetworking.ts#L50-L78
pindab0ter/raycast-hue:src/lib/createHueClient.ts#L20-L56

@stupid-beard
Copy link

stupid-beard commented May 25, 2023

You can still use rejectUnauthorized if you override the https agent in the axios config. For example:

const axios = require('axios')
const https = require('https')

const instance = axios.create({
  // ... other options ...
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
})

Obviously not a great idea for production use, but this worked for me.

@DeepakSharma04
Copy link

You can still use rejectUnauthorized if you override the https agent in the axios config. For example:

const axios = require('axios')
const https = require('https')

const instance = axios.create({
  // ... other options ...
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
})

Obviously not a great idea for production use, but this worked for me.

How to import https ,i'm getting is error ---> https could not be found within the project or in these directories: node_modules../../../node_module

@zhibirc
Copy link

zhibirc commented Dec 13, 2023

@DeepakSharma04

How to import https...

import { Agent } from 'node:https';

@sabriyasar
Copy link

Can you share how to use it in its most current form? It still gives me an error.

net::ERR_CERT_AUTHORITY_INVALID

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests