0

I am running the following script in a Windows command prompt with node myscript.js. The script requests a web application which is using Windows Authentication. I expect to receive status code 200. But the script returns a 401 Unauthenticated.

let request = require('request');

console.log(process.env.USERDOMAIN);
console.log(process.env.USERNAME);

request('http://internalurl',
    function (error, response, body){
        if (!error && response.statusCode == 200){
            console.log('request successful!');

            var input = JSON.parse(body);
        }   
            console.log(response);
    });

The process.env.USERNAME displays my current username which should have access to the web application. Because of this I am assuming that the script is running under the correct user account. What is the best practice to login into the web application?

Citizen SP
  • 1,411
  • 7
  • 36
  • 68

1 Answers1

0

It's normal to receive a 401 message when using Windows authentication - that's the first step in the Windows authentication process. The WWW-Authenticate header in the 401 response then tells you which authentication mechanisms are available (either NTLM or Negotiate).

The accepted answer to this question describes the process in more detail: https://stackoverflow.com/a/13960538/1202807

However, that answer doesn't provide a solution for a node client. But the last answer to that question does give an example of how to do it with node-libcurl:

var endpoint = urlString;
var url = require("url");
var endpointUrl = url.parse(endpoint);

var Curl = require( 'node-libcurl' ).Curl;
var curl = new Curl();

curl.setOpt( 'USERNAME', '' );
//curl.setOpt( 'VERBOSE', 1 );
curl.setOpt( 'URL', endpoint );
curl.setOpt( 'HTTPAUTH', Curl.auth.NEGOTIATE );
curl.setOpt( 'NOPROXY', endpointUrl.hostname );

curl.on( 'end', function( statusCode, body, headers ) {

    if (statusCode === 200) {
        console.log(body);
        cb(null, { statusCode, body, headers } ); 
    } else {
        cb(new Error(), { statusCode, body, headers } ); 
    }

    this.close();
});

curl.on( 'error', curl.close.bind( curl ) );
curl.perform();

I've never done this in node myself though, so that's about all the help I can be.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84