Session Cookies expiration handling in ASP.NET MVC 3 while using WIF and jquery ajax requests

I my project I'm using WIF (but this is not really important for the context of this question. You can use alternative framework which handles your authentication. Question is about dealing with authentication failures while performing ajax requests). Nevertheless, in my case I've written custom server logic which inherits from ClaimsAuthenticationManager , and handles authentication:

public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
{
    if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
    {
        // add some custom claims
    }
    return incomingPrincipal;
}

Now, after I delete all Session Cookies , end then enter any page again, I'm redirected to the login page served by WIF, and I'm requested to log again. Everything works as expected.

But if I make an ajax request instead, I've got an error, which is intercepted by this:

$(document).ready(function () {
    $.ajaxSetup({
        error: function (XMLHttpRequest, textStatus, errorThrown) {            
            // do something
        }
    });
});

Unfortunately XMLHttpRequest object does not return any meaningful message, based on which I could handle this kind of error in any other way as others. In this particular case I just want application to redirect to the login page - as the normal request does.

在这里输入图像描述

While the ajax call is executing, the method Authenticate from ClaimsAuthenticationManager is invoked. Identity.IsAuthenticated returns false, method ends and all is done. Even the OnAuthorization method from BaseController is not invoked, so I cannot pass any status to the ajax result object.

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.Request.IsAjaxRequest() && !User.Identity.IsAuthenticated)
    {
        //do something, for example pass custom result to filterContext
    }
    base.OnAuthorization(filterContext);
}

How to resolve the puzzle ?


链接地址: http://www.djcxy.com/p/1962.html

上一篇: 403 Forbidden vs 401未经授权的HTTP响应

下一篇: 在使用WIF和jQuery ajax请求时ASP.NET MVC 3中的会话Cookie过期处理