23

I am developing an HTML5 mobile app, which communicates with WebServices. WebServices use NTLM authentication protocol. I am having difficulties to handle the handshake via JavaScript. NTLM sends the 401 unauthorized as response to my POST, which I have not found any way to respond to.

Is NTLM authentication possible with JavaScript? Should I build a proxy web service with e.g. basic authentication in-between?

my jQuery call is something like...

$.ajax({
                    type: "POST",
                    url: URL,
                    contentType: "text/xml",
                    dataType: "xml",
                    data: soapRequest,
                    username: 'username',
                    password: 'password',
                    xhrFields: {
                        withCredentials: true
                    },
                    success: processSuccess,
                    error: processError
});
Levente Kurusa
  • 1,858
  • 14
  • 18
TryCatch
  • 231
  • 1
  • 2
  • 4

4 Answers4

12

You don't have to respond to the NTLM (Integrated Windows Authentication) challenge, your browser should do it for you, if properly configured. A number of additional complications are likely too.

Step 1 - Browser

Check that the browser can access and send your credentials with an NTLM web application or by hitting the software you're developing directly first.

Step 2 - JavaScript withCredentials attribute

The 401 Unauthorized error received and the symptoms described are exactly the same when I had failed to set the 'withCredentials' attribute to 'true'. I'm not familiar with jQuery, but make sure your attempt at setting that attribute is succeeding.

This example works for me:

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://localhost:44377/SomeService", true);
xhttp.withCredentials = true;
xhttp.send();
xhttp.onreadystatechange = function(){
  if (xhttp.readyState === XMLHttpRequest.DONE) {
    if (xhttp.status === 200)
      doSomething(xhttp.responseText);
    else
      console.log('There was a problem with the request.');
  }
};

Step 3 - Server side enable CORS (Optional)

I suspect a major reason people end up at this question is that they are developing one component on their workstation with another component hosted elsewhere. This causes Cross-Origin Resource Sharing (CORS) issues. There are two solutions:

  1. Disable CORS in your browser - good for development when ultimately your work will be deployed on the same origin as the resource your code is accessing.
  2. Enable CORS on your server - there is ample reading on the broader internet, but this basically involves sending headers enabling CORS.

In short, to enable CORS with credentials you must:

  • Send a 'Access-Control-Allow-Origin' header that matches the origin of the served page ... this cannot be '*'
  • Send a 'Access-Control-Allow-Credentials' with value 'true'

Here is my working .NET code sample in my global.asax file. I think its pretty easy to see what's going on and translate to other languages if needed.

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.HttpMethod == "OPTIONS")
    {
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        Response.AddHeader("Access-Control-Max-Age", "1728000");
        Response.End();
    }
    else
    {
        Response.AddHeader("Access-Control-Allow-Credentials", "true");

        if (Request.Headers["Origin"] != null)
            Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]);
        else
            Response.AddHeader("Access-Control-Allow-Origin" , "*"); // Last ditch attempt!
    }
}
QA Collective
  • 2,222
  • 21
  • 34
5

As far as I have seen, no one has implemented Windows Integrated/NTLM auth with AJAX, although it should be possible (I'm considering doing it for a current project to combine form authentication with the WindowsTokenRoleProvider)

The basic workflow should breakdown like this (based on articles here and here):

  1. do a GET request with a base64-encoded type-1 NTLM message in the "Authorization" header
  2. take the base64-encoded type-2 NTLM message out of the "WWW-Authenticate" header in the 401 response.
  3. perform the NTLM operation on the noonce recieved in the previous step (sorry I don't have a code example yet)
  4. perform a final GET with a base64-encoded type-3 NTLM message in the "Authorization" header. This should return a 200.

NTLM auth over HTTP is more of a CHAP implementation using HTTP than it is an authorized HTTP request.

I'll update you if I actually get around to implementing this. Sorry I couldn't be of more help.

fawaad
  • 341
  • 6
  • 12
Doct0rZ
  • 153
  • 1
  • 2
  • 7
  • 1
    All four of the steps you outlined above should be done automatically by the browser. I have a working implementation of this in production. – QA Collective Jul 31 '18 at 03:43
  • 1
    @QACollective and how do I get it in my website? When I hit the service directly yes, my browser does it and it works. But that doesnt stop the fetch call in my sample wesite to get 401ed – Hobbamok Dec 07 '20 at 10:56
4

The problem is that you can't get the currently logged in domain/user via javascript (or if you can I've never found a solution).

If you already know the domain, username and password you could use something like https://github.com/erlandranvinge/ntlm.js/tree/master

However I think going down this method for single sign on is going to be frustrating in the long run.

We ended up doing NTLM authentication in a hidden iframe and accessing the iframe via javascript.

Kinetic
  • 1,714
  • 1
  • 13
  • 38
  • This is good, note: there is not a way to do CORS (or JSONP) using this as far as I can tell. – Gram Jun 21 '16 at 20:32
0

Yeah NTLM isn't very fun. But you might want to try this, https://github.com/tcr/node-ntlm/blob/master/README.md

MinimalMaximizer
  • 392
  • 1
  • 4
  • 18