Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax request hitting error function before HandleUnauthorizedRequest

I have an PhoneGap app that is communicating with a C# service for it's data. The user has to be logged in for them to access any of this so I have a AuthorizeAttribute on my controller. This works fine and rightly, throws an to my app. The problem for me is that in my AuthorizeAttribute I am overriding the HandleUnauthorizedRequest method and it should be returning a 401. In fact, it probably is, it's just that the Ajax handler hits the error function before my override method has returned.

AuthorizeAttribute

public class AppCustomAuthorization : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.HttpContext.Response.StatusCode = 401;
        filterContext.HttpContext.Response.End();

        base.HandleUnauthorizedRequest(filterContext);
    }
}

Ajax

$.ajax({
    type: "GET",
    url: url + "checkin/app/info",
    dataType: "json",
    success: function(d) {
        // Do stuff
    },
    error: function (xhr, textStatus, errorThrown) {
        app.showError(errorThrown); // Status code is 0
    }
});

When I look at the Network requests, it seems that my get request is cancelled. Originally, I assumed this is because my authorize attribute is causing it cancel the request, but then, it seems to cancel before it hits my handler.

like image 257
ediblecode Avatar asked Jan 27 '26 03:01

ediblecode


2 Answers

This might be because of the Same Origin Policy. Check this out:

http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html

like image 81
Maximosaic Avatar answered Jan 29 '26 16:01

Maximosaic


Just in order to close the complete the question, the reason I was seeing a response code of 0 is because:

A status code of "0" usually means the user navigated to a different page before the AJAX call completed

I got this from this SO answer, which has over 70,000 views at the time of writing, so I guess this problem can occur a lot. This obviously led me to look at what could be causing my app to navigate elsewhere and sure enough, in my code I had:

$('[data-role=page]').on('pageshow', function (event, ui) {
if ($(location).attr('pathname').indexOf('login.html') == -1)
    if (window.localStorage['UserName'] == null || window.localStorage['Password'] == null) 
        window.location = "login.html";
}):

As a workaround from the early stages of development from the app as a primitive type of checking the user was actually logged in.

like image 39
ediblecode Avatar answered Jan 29 '26 17:01

ediblecode