When attempt logoff, The provided anti-forgery token was meant for user “XXXX”, but the current user is “”

后端 未结 2 675
不知归路
不知归路 2020-12-14 08:51

I have an MVC 4 app and having issues when the forms session expires and then the user tries to logoff.

Ex. timeout is set to 5 min. User logs in. User does nothing

相关标签:
2条回答
  • 2020-12-14 09:04

    The answer of @cem was really helpful for me and I added a small change to include the scenario of ajax calls with antiforgerytoken and expired session.

    public void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception as HttpAntiForgeryException;
        if (exception == null) return;
    
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.HttpContext.Response.StatusCode = 403;
            filterContext.ExceptionHandled = true;
        }
        else
        {
            var routeValues = new RouteValueDictionary
            {
                ["controller"] = "Account",
                ["action"] = "Login"
            };
            filterContext.Result = new RedirectToRouteResult(routeValues);
            filterContext.ExceptionHandled = true;
        }
    }
    

    ... and on the client side you can add a global ajax error handler to redirect to the login screen...

    $.ajaxSetup({
        error: function (x) {
            if (x.status === 403) {
                window.location = "/Account/Login";
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-14 09:16

    Actually you can handle it with IExceptionFilter, that will redirect to the /Account/Login

    public class HandleAntiForgeryError : ActionFilterAttribute, IExceptionFilter
    {
        #region IExceptionFilter Members
    
        public void OnException(ExceptionContext filterContext)
        {
            var exception = filterContext.Exception as HttpAntiForgeryException;
            if (exception != null)
            {
                var routeValues = new RouteValueDictionary();
                routeValues["controller"] = "Account";
                routeValues["action"] = "Login";
                filterContext.Result = new RedirectToRouteResult(routeValues);
                filterContext.ExceptionHandled = true;
            }
        }
    
        #endregion
    }
    
    [HandleAntiForgeryError]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff() 
    {
    }
    

    Also you can use [HandleError(ExceptionType=typeof(HttpAntiForgeryException)...] but it requires customErrors On.

    0 讨论(0)
提交回复
热议问题