2

I've a controller with authorize attribute where i do stuff like login, logout. After a succued login action with a javascript call, all other actions still returning 401 Unauthorized error. In my example using the logout action returning 401 and leads to my problem.

Actions

[HttpGet]
[AllowAnonymous]
[Mvc.ValidateAntiForgeryToken]
public bool Login(string param)
{
    var parameters = param.Split('/');
    var username = parameters[0];
    var password = parameters[1];

    if (WebSecurity.Login(username, password, true))
        return true;
    return false;
}

[HttpGet]
[Mvc.ValidateAntiForgeryToken]
public void Logout()
{
    WebSecurity.Logout();
}

Ajax

public login(username: string, password: string): bool {
    var url = this.baseUrl + "Account/Login/" +
        encodeURIComponent(username) + "/" + encodeURIComponent(password);
    var xhr: JQueryXHR = $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false
    });
    if (xhr.status == 200)
        if (xhr.responseText == "true")
            return true;
    return false;
}

public logout(): bool {
    var url = this.baseUrl + "Account/Logout/";
    var deferred: JQueryDeferred = $.Deferred();
    var xhr = $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        cache: false,
        async: false
    });
    if (xhr.status == 200)
        return true;
    return false;
}
MR.ABC
  • 4,712
  • 13
  • 44
  • 88
  • Seems to me you're not actually checking if `xhr.status` is 200 - there's a typo (`=` rather than `==`), so you're actually *setting* it to 200, then checking that result. Although that shouldn't make it not work - `login()` will still return `false` if `responseText` isn't `"true"`, and `logout()` will always return `true`. – JimmiTh Jul 14 '13 at 15:53
  • thanks for your hint but this actually does not solve my problem. – MR.ABC Jul 14 '13 at 17:06
  • 1
    Check and see if a _RequestVerificationToken exists. Read this SO question: http://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken – ScottE Jul 14 '13 at 17:09
  • That was the problem. Removed the ValidateAntiForgeryToken attribute. This solved the issue. – MR.ABC Jul 14 '13 at 17:14

0 Answers0