3

When I am login with user's credential, first time no error while login to application,

but when I logoff and again login with other user's credential got an error

The provided anti-forgery token was meant for user "UserName", but the current user is "".

I am implementing AntiForgoryToken and IPrincipal with asp.net mvc 5

I tried :

  1. AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; in Application_Start()

  2. I already refered this link When attempt logoff, The provided anti-forgery token was meant for user "XXXX", but the current user is ""

How can I fix this error ?

Thanks in advance.

Community
  • 1
  • 1
gaurav bhavsar
  • 2,033
  • 2
  • 22
  • 36

2 Answers2

2

I found my IIS instance had both Anonymous and Windows authentication enabled which was causing this exception for my application

Authentication Settings both enabled

This setting seems to be the cause of this exception. It seems that the ValidateAntiForgeryToken action filter was using the current user populated with an empty string in the Anon authentication and then attempting to match it against the token which was populated using Win authentication.

By turning off either Windows or Anonymous authentication (for my application I switched off Anon authentication,) the tokens now match up.

Authentication Settings one enabled

This setting can be altered in IIS manager or in the web.config file like so

<system.webServer>
    <security>
      <authentication>
        <anonymousAuthentication enabled="false" />
        <windowsAuthentication enabled="true" />
      </authentication>
    </security>
</system.webServer>
0

You don't really need to check for the antiforgery token on the post method of your login.

Antiforgery tokens provide protection from CSRF attacks. A CSRF attack happens when a malicious script/link posts an HTTP request on your behalf without your knowledge or consent. When an antiforgery token is embedded on your page, the server can check for this token when it receives the request to verify that the request indeed came from the page. A request from a malicious script or link will not have the token and will fail.

So, all other post actions that you want to protect should be decorated them with the [Authorize] and [ValidateAntiForgeryToken] attributes. The login post method, however, doesn't need either of these attributes.

Update: It is really needed. See answer in Stephen Muecke's comment.

OJ Raqueño
  • 4,471
  • 2
  • 17
  • 30
  • Interesting !! So how to protect login and user's credential as http://security.stackexchange.com/questions/2120/when-the-use-of-a-antiforgerytoken-is-not-required-needed – gaurav bhavsar Dec 18 '15 at 17:35
  • 2
    You most definitely do need the token on a login method and I suggest you read [this answer](http://security.stackexchange.com/questions/2120/when-the-use-of-a-antiforgerytoken-is-not-required-needed) –  Jan 17 '16 at 10:32