I'm getting a Runtime error
related the the anti-forgery attribute.
Perform the following steps:
- Create an MVC web application and start
- Register joe@acme.org
- Sign out
- Register jane@acme.org
- Sign out
- Login as joe@acme.org
- Hit the back button
- Login as jane@acme.org
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?
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:
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.
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 fromHandleErrorAttribute
. Override theOnException
method.Go to your
FilterConfig
class and register the attribute as a global filter.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.
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: