'jQuery Ajax Web API call returns 401 unauthorized error when set only Windows authentication in IIS

We have our Web API hosted in IIS with only Windows authentication. We are calling that API from our Angular project and it is working fine.

Now we are creating a jQuery Ajax method to call that API method (which has an AllowAnonymous annotation).

This is my jQuery code:

var settings = {

  "crossDomain": true,
  "url": URL,
  "contentType": "application/json; charset=utf-8",  
  "dataType": "json",
  "data" : JSON.stringify(Model); // model contains json object.
  "method": "POST"     
}  
$.ajax(settings).done(function (response) { console.log(response);});

I have almost tried all possible solutions as below :

  1. Set CrossDomain : true in Ajax call

  2. Set header with accept type and Allow_origin_method to *

  3. cache : true

  4. In IIS set NTLM and Negotiate in provider of Windows authentication

  5. In IIS port give full rights to user in permission

To replicate the issue, we can create a simple Web API and jQuery to call one of method of that API. Host both on IIS on different port and also set Windows authentication for Web API



Solution 1:[1]

Try setting the withCredentials: true in AJAX call. It will pass on the authentication details to API.

 $.ajax({
            type: 'GET',
            url: Url,
            xhrFields: {
                withCredentials: true
            },
            success: function (data, textStatus, jqXHR) {
                console.log(data);                
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
                alert('A problem occurred while trying to load data from ' + Url);
            },
            complete: function (jqXHR, textStatus) {
                if (textStatus == 'error') {
                    console.log(jqXHR.responseText);
                }
            }
        });

Setting withCredentials has no effect on same-site requests.

for more information on this property, XMLHttpRequest - WithCredentials

Solution 2:[2]

Try changing ajax code for the url to url: '@Url.Action("Action", "Controller")' This fixed my issue when the app was published to IIS displaying a login popup and causing a 401.2 error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bhavjot
Solution 2 Richard Tomassetti