Deny browser authentication dialog on 401

I am running a web-api web service inside an MVC4 forms authentication website. The forms authentication application uses web-api web services. I protected web-api with the [Login] attribute. Now, when I call web-api from the MVC4 application while the authorization ticket expires, I get an ugly browser login dialog (which does not work with forms authentication). I do not get this on my dev machine (IIS7.5), which I really don't understand! How can I prevent this dialog from appearing? I need to get only 401.

+4
source share
2 answers

Moved the site to the IIS8 server, and now the problem has disappeared ...

0
source

John Galloway perfectly explains this in his ASP.NET Web API screencast - Authorization (Highly Recommended Viewing)

For some api controller, for example below, where you used the Authorize attribute.

 [Authorize] public class CommentsController : ApiController { ... } 

He says: if a client makes an unauthorized request, AuthorizationFilter does the only thing that makes sense for the HTTP API - it returns an HTTP 401 status code, authorization is required. Again, we returned to the importance of using HTTP for the API - we don’t need to order anything, any client on any platform will know what the HTTP 401 response means.

This is a solution for the client to decide what to do when they receive 401. In this JavaScript / browser-based example, we simply redirect to the client login page.

 $(function () { $("#getCommentsFormsAuth").click(function () { viewModel.comments([]); $.ajax({ url: "/api/comments", accepts: "application/json", cache: false, statusCode: { 200: function(data) { viewModel.comments(data); }, 401: function(jqXHR, textStatus, errorThrown) { self.location = '/Account/Login/'; } } }); }); }); 

Here, in the example, if 401 meets you to decide what needs to be done.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1441371/


All Articles