.NET C#: How to handle forms authentication expiration during an AJAX call

江枫思渺然 提交于 2019-12-06 02:32:56

so the Account/Login action get's executed when the ticket expires

public Action Login()
{
   if(Request.IsAjaxRequest())
   return Content(@"<meta http-equiv="refresh" content="1" />");
   //if it is ajax request the div will be filled with this meta tag which will refresh the page


  return View();
}
 public class BasicAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        var user = filterContext.HttpContext.User;
        if (user == null || !user.Identity.IsAuthenticated)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { redirectTo = FormsAuthentication.LoginUrl }
                };
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //  throw new NotImplementedException();
    }
}

and then you can use in following way

$.get('/foo', function(result) {
if (result.redirectTo) {
    window.location.href = result.redirectTo;
} else {
    // standard stuff
}

});

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!