Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "Back" button and the anti-forgery token

Tags:

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?

like image 832
WhiskerBiscuit Avatar asked Jun 24 '14 00:06

WhiskerBiscuit


People also ask

What is an anti-forgery token?

In general, the anti-forgery-token is an HTML hidden input that that's rendered for you to avoid CSRF attacks. Broadly, it works by comparing the value that the server sent down to the client to what the client sends back on the post.

How do you validate anti-forgery tokens?

The feature doesn't prevent any other type of data forgery or tampering based attacks. To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html. AntiForgeryToken() in the forms posting to the method.

How do you fix Anti-forgery cookies?

Remove the anti-forgery validation from the login page Anti-forgery token's main purpose is to prevent attacker using authentication cookie for doing things on behalf of the actual user. Since the user isn't authenticated yet in the login page, there are customers removing the validation.

Where are anti-forgery tokens stored?

The token is stored as a cookie that's sent with every request the client makes. Generating and validating this cookie is performed by the Cookie Authentication Middleware.


1 Answers

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.

like image 140
julealgon Avatar answered Sep 24 '22 12:09

julealgon