1

Bellow code functioning fine, but when authorization header come with empty token from php code (Eg- 'Authorization: bearer '), node.js application get crash. I'm using "passport-azure-ad" node module. I checked with Post man, it's validate the token, but when the request come from php curl request, application get crash. The reason for this, http header set two times in "passport-azure-ad" node module. I couldn't catch this error.

router.get('/getUser', passport.authenticate('oauth-bearer', {
    session: false,
    tenantIdOrName: TENANT
}), function (req, token, done) {
    // Send response
});

Crash error trace - _http_outgoing.js:356 throw new Error('Can\'t set headers after they are sent.'); ^

Error: Can't set headers after they are sent. at \node_modules\passport\lib\middleware\authenticate.js:156:13)

PHP code = >

$headers = array ('Authorization: bearer ' . $Requestheader['id_token']);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ( $ch, CURLOPT_URL, 'http://serverhost/auth/getUser' );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
return curl_exec ( $ch );

How can I handle this error from my side, Thank you.

Sudharshan
  • 348
  • 1
  • 9
  • 1
    Did it work when you send the validate token instead of empty token from PHP? And what's version of `passport-azure-ad` you were developing? What's the exact curl request code? – Fei Xue Oct 10 '17 at 02:54
  • @FeiXue, Thank you for your response, Yes, It's working perfectly when I pass valid or invalid token through php curl. I'm using 3.0.8 version of "passport-azure-ad". I edited question with php code. – Sudharshan Oct 10 '17 at 04:24

1 Answers1

0

The Node.js is being run in a single thread, it will crash when the error is not handled. Here is a very helpful thread about Exception Handling in Node.js:

Node.js Best Practice Exception Handling

Fei Xue
  • 14,369
  • 1
  • 19
  • 27
  • Yes we can catch the error globally, but I'm looking for catch the error at exact place. – Sudharshan Oct 10 '17 at 06:37
  • I am trying to reproduce the issue using [WebAPI-Bearer-NodeJS](https://github.com/AzureADQuickStarts/WebAPI-Bearer-NodeJS/blob/master/node-server/app.js) however failed. The code sample will not crash no matter whether the token is provided. And based on the error message, it seems that the application set the headers after the response was sent. And refer [this thread](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) for the same error message. – Fei Xue Oct 10 '17 at 08:04