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.
src="https://i.stack.imgur.com/hlb4H.jpg" alt="enter image description
here">
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 ?
No comments:
Post a Comment