25

I'm getting a Runtime error related the the anti-forgery attribute.

Perform the following steps:

  1. Create an MVC web application and start
  2. Register [email protected]
  3. Sign out
  4. Register [email protected]
  5. Sign out
  6. Login as [email protected]
  7. Hit the back button
  8. Login as [email protected]

Error: The provided anti-forgery token was meant for a different claims-based user than the current user.

What can be done to prevent this error from occurring?

4 Answers 4

35

I had this same problem just now and solved it by disabling caching of the login view. It actually makes a lot of sense, and requires no code or exception handling.

My log in controller method now looks like this:

[AllowAnonymous]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult LogOn(Uri returnUrl)

When caching is disabled and the user clicks the back button on the browser, a new request is made to the server and the page is delivered again, with the antiforgery token set to the correct user.

I feel this is a much cleaner, easier and logical approach to the problem.

7
  • When I do login, then logout and for the last login again (all this with the same user), this code not works for me. On second login returns the error: "The provided anti-forgery token was meant for a different claims-based user than the current user".
    – mggSoft
    Jan 20, 2015 at 8:52
  • Worked well for me, nice idea
    – DennisWelu
    Apr 9, 2015 at 23:51
  • I found that chrome shows an ERR_CACHE_MISS error message if you remove the cache for POST requests and navigate to it using the back button
    – ajbeaven
    Sep 16, 2015 at 21:23
  • I had this problem and there were two causes: (1) users double-clicking the "log on" button; and (2) the login page being erroneously cached as described here. You have to tell the client browser not to cache the login page, which I think is good security practice anyway.
    – philw
    Oct 2, 2015 at 8:45
  • Worked well for me. Incidentally, this is also a workaround for the well-documented but extant bug in Firefox when you disable a button with Javascript and it stays disabled upon page refresh and after pressing back. Google "firefox buttons stay disabled"
    – nmit026
    Nov 20, 2016 at 23:12
25

This is one way of ignoring the error and returning the user to the login screen. It's just an example.

Create a new class called HandleAntiforgeryTokenErrorAttribute that inherits from HandleErrorAttribute. Override the OnException method.

public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(new { action = "Login", controller = "Account" }));
    }
}

Go to your FilterConfig class and register the attribute as a global filter.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new HandleAntiforgeryTokenErrorAttribute()
            { ExceptionType = typeof(HttpAntiForgeryException) }
        );
    }
}
8
  • Where would that go? The error occurs before public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) is even called Jun 24, 2014 at 3:11
  • @RowanFreeman No the given solution is not working. Before hitting Login ActionResult its giving error. The provided anti-forgery token was meant for user "", but the current user is "[email protected]".
    – RajeshKdev
    Jun 24, 2014 at 4:24
  • Yeah, nice pick-up. I forgot that this would be occurring early in the pipeline. I'll update my answer. Jun 24, 2014 at 4:28
  • 3
    Thank you for the update. Hence the above code is handling the error nicely. But willing to know, what is the proper way? Since the user is already logged in. But its redirecting me to login. from there i'm able to navigate any page without login. Hope you got the functional problem.
    – RajeshKdev
    Jun 24, 2014 at 6:05
  • I'm not sure what you mean by proper way. The application already handles it properly by throwing an exception - the user is trying to do something that is invalid. You can redirect them to a friendly error page or you can ignore the error. Jun 24, 2014 at 6:32
4

Accepted answers just catches all exceptions, because it doesn't filter them by exception type like original HandleErrorAttribute does.

Use the following code to only handle HttpAntiForgeryException:

public static class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new HandleAntiforgeryTokenErrorAttribute());
    }
}

public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
    public HandleAntiforgeryTokenErrorAttribute()
    {
        ExceptionType = typeof(HttpAntiForgeryException);
    }

    public override void OnException(ExceptionContext filterContext)
    {
        if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
        {
            return;
        }

        filterContext.ExceptionHandled = true;
        filterContext.Result =
            new RedirectToRouteResult(
                new RouteValueDictionary(
                    new {
                            area = string.Empty,
                            action = "Index",
                            controller = "Home"
                        }));

    }
}
1

Cached old pages, brought back to life witht the back-button, contain old anti-forgery tokens and cause the exception. The global filter solution by Rowan Freeman redirects to the login page. However, this caching problem is also causing the site to serve an old login page with an old token. Submitting the form will cause the same exception. Ergo, IMO, both solutions (Rowan Freeman's and julealgon's) solutions should be implemented.

Theorectically, avoiding caching for every page should do the trick aswell, but at a significant cost (latency, bandwidth). I choose to reroute to the login to be able to use caching and avoid caching on the login to mitigate the exception, i.e. implementing both.

2
  • This should be a comment, but you have insufficient rep. Please explain why the solution by @julealgon is not enough by itself. It appears to do the trick. Dec 1, 2015 at 10:37
  • 1
    The solution by julealgon will only work if the browser respects the instruction to disable the cache (in some instances Internet Explorer can and will ignore this and cache the page anyway). Rowan's solution is a good fall back in this case.
    – hobwell
    Feb 29, 2016 at 20:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.