简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM