سؤال

My main goal is to understand what exactly occurs during an authorization process between a client (browser) using ajax and asp.net web api back-end.

So initially, I make a simple GET request to one of my controllers (allowing "Access-Control-Allow-Origin") via ajax from my browser. I take the response that I want and everything is OK so far.

Then, I am setting an authorize attribute on the same controller on web api and I make again a simple GET request in order to study the result. So, with the help of firebug, I see that there is a "NetworkError: 401 Unauthorized - localhost/api/values".

Besides, on the result object I see the following values: readyState : 0, responseText : "", status : 0, statusText : "error". Is this normal? Should not I see for example status : 401? I think I could use the accepted solution of this thread: Unauthorized AJAX request succeeds but I prefer to check a potential 401 result more strictly.

One thought that I made is that maybe the asp.net web API by default, when you use the authorize attribute, on an unauthorized response does not include the "Access-Control-Allow-Origin" header, so I added globally a custom action filter which adds the "Access-Control-Allow-Origin" to each response, but it did not solve my problem, so I guess this is not the case.

هل كانت مفيدة؟

المحلول

I found a solution. My assumption concerning what caused this problem was eventually proved accurate. When an unauthorized request was arriving to a controller, which was requiring authorization (using the authorize attribute), then the response was not including the header "Access-Control-Allow-Origin". Consequently the status of the jqXHR on the client was 0 instead of 401.

So I added the "Access-Control-Allow-Origin" to asp.net web api Web.config and finally worked properly.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top