Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve: The provided anti-forgery token was meant for a different claims-based user than the current user

Tags:

c#

asp.net-mvc

I am getting this error:

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

and I am not sure how to correct this..

I have a MVC5 site and in this site I have a login page.

This is the scenario that it occurs on.

  1. User AAA logs in. (No issues)
  2. I attempt to access a view where the user does not have access.
    • I have the class decorated with an Authorize(Roles="aa")
  3. The view then logs the user off and puts them back to the login page.
  4. User AAA logs in. (This time I get the error mentioned above)

To note:
I am using customErrors and this is where I see the error message.

When I log the user out I am running this method:

[HttpGet]
public void SignOut()
{
    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
    authenticationManager.SignOut(MyAuthentication.ApplicationCookie);
}

Could I possibly be missing something on the SignOut?

UPDATE:
This only occurs because of step #2 listed above.
If I log in, then log out (calling same code) then log back in, then I do not have this issue.

like image 588
John Doe Avatar asked Jan 03 '17 14:01

John Doe


1 Answers

I think you've neglected to post some relevant code. The Signout action you have returns void. If you were to access this action directly in the browser, then the user would get a blank page after being signed out with no way to progress forward. As a result, I can only assume you are either calling it via AJAX or calling as a method from another action.

The way anti-forgery works in MVC is that a cookie is set on the user's machine containing a unique generated token. If the user is logged in, their username is used to compose that token. In order for a new cookie, without a username to be set, the user must be logged out and a new request must occur to set the new cookie. If you merely log the user out without doing a redirect or something, the new user-less cookie will not have been set yet. Then, when the user posts, the old user-based cookie is sent back while MVC is looking for the new user-less cookie, and boom: there's your exception.

Like I said, you haven't posted enough code to determine exactly why or where this is occurring, but simply, make sure there is a new request made after logging the user out, so the new cookie can be set.

like image 119
Chris Pratt Avatar answered Oct 26 '22 23:10

Chris Pratt