开发者

Authorize with JsonReult action jQuery ajax returned status code 200 when not authorized

I have JsonResult action which required authentication and special role

[Authorize(Roles = "User")]
public virtual JsonResult Cancel()
{
 //...
}

But when for example i log off and hit this action with jQuery ajax i could see that status code is 200, but it is should be 401.

$.ajax({
                url: "/Cancel/",
                type:   "POST",
                dataType: "text",
                cache: false,
                success: function (data, textStatus, xhr) {
                    alert(xhr.status); //200 here when unauthorized
                }

});

So I really not able to execute the controller logic because it is not authorized, i checked t开发者_如何学编程hat on debug, but why i am getting status code 200 in jquery ajax?

UPDATED:

In Fiddler it is saying status code 302 and i could see that request to /Acount/Login was made after /Cancel request.

/Cancel - 302
/Acount/Login - 200

In Chrome network Status Code:302 Found and also i could see that login controller(/Acount/Login) getting called after /Cancel was called.

/Cancel - 302
/Acount/Login - 200

Complete request details in Opera network

Could someone explain whats happening, why jquery didn't get correct status code?

Really what i want to do - a want to get correct status code and if it is 401 i want to redirect user to login page (window.location.href = " /Acount/Login")

Request details

POST /Cancel/ HTTP/1.1 
User-Agent: Opera/9.80 (Windows NT 6.1; U; en) Presto/2.9.168 Version/11.50
Host: localhost:999
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate
Referer: http://localhost:999/Action
Cookie: style=normalText; ASP.NET_SessionId=latzewpi3kqmkq4meljv0ln5
Connection: Keep-Alive
Content-Length: 0
Accept: text/plain, */*; q=0.01
X-Requested-With: XMLHttpRequest
Content-Type: text/xml; charset=utf-8
Content-Transfer-Encoding: binary

Response details

HTTP/1.1 302 Found 
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: /Account/LogOn?ReturnUrl=%2fCancel%2f
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 11 Aug 2011 03:04:53 GMT
Content-Length: 169


FormsAuthentication have handler in its http module, that will redirect all 401 responses to login page instead of error page.

Looking at source code of FormsAuthenticationModule there should be (quite ugly) workaround - if you append ReturnUrl=/ to your query string, the module should do no redirection.

The best solution is probably to write own http module for authentication - you can open FormsAuthenticationModule in reflector and use it as reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜