Anti forgery token is meant for user "" but the current user is "username"

94,733

Solution 1

This is happening because the anti-forgery token embeds the username of the user as part of the encrypted token for better validation. When you first call the @Html.AntiForgeryToken() the user is not logged in so the token will have an empty string for the username, after the user logs in, if you do not replace the anti-forgery token it will not pass validation because the initial token was for anonymous user and now we have an authenticated user with a known username.

You have a few options to solve this problem:

  1. Just this time let your SPA do a full POST and when the page reloads it will have an anti-forgery token with the updated username embedded.

  2. Have a partial view with just @Html.AntiForgeryToken() and right after logging in, do another AJAX request and replace your existing anti-forgery token with the response of the request.

Note that setting AntiForgeryConfig.SuppressIdentityHeuristicChecks = true does not disable username validation, it simply changes how that validation works. See the ASP.NET MVC docs, the source code where that property is read, and the source code where the username in the token is validated regardless of the value of that config.

Solution 2

To fix the error you need to place the OutputCache Data Annotation on the Get ActionResult of Login page as:

[OutputCache(NoStore=true, Duration = 0, VaryByParam= "None")] 
public ActionResult Login(string returnUrl)

Solution 3

The message appears when you login when you are already authenticated.

This Helper does exactly the same thing as [ValidateAntiForgeryToken] attribute.

System.Web.Helpers.AntiForgery.Validate()

Remove the [ValidateAntiForgeryToken] attribut from controller and place this helper in action methode.

So when user is already authentificated, redirect to the home page or if not continue with the verification of the valid anti-forgery token after this verification.

if (User.Identity.IsAuthenticated)
{
    return RedirectToAction("Index", "Home");
}

System.Web.Helpers.AntiForgery.Validate();

To try to reproduce the error, proceed as follows: If you are on your login page and you are not authenticated. If you duplicate the tab and you login with the second tab. And if you come back to the first tab on the login page and you try to log in without reloading the page ... you have this error.

Solution 4

It happens a lot of times with my application, so I decided to google for it!

I found a simple explanation about this error! The user are double-clicking the button for login! You can see another user talking about that on the link below:

MVC 4 provided anti-forgery token was meant for user "" but the current user is "user"

I hope it helps! =)

Solution 5

I had the same problem, and this dirty hack got it fixed, at least until I can fix it in a cleaner way.

    public ActionResult Login(string returnUrl)
    {
        if (AuthenticationManager.User.Identity.IsAuthenticated)
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Login");
        }

...

Share:
94,733
parliament
Author by

parliament

Serial Entrepreneur Full Stack Developer (C#/AngularJS/D3.js) Contact me if you want to work on cool shit with me. Currently in the bitcoin space, starting a cryptocurrency exchange. Also have a body of work on automated trading systems. [email protected]

Updated on December 01, 2020

Comments

  • parliament
    parliament over 3 years

    I'm building a single page application and experiencing an issue with anti-forgery tokens.

    I know why the issue happens I just don't know how to fix it.

    I get the error when the following happens:

    1. Non-logged-in user loads a dialog (with a generated anti-forgery token)
    2. User closes dialog
    3. User logs in
    4. User opens the same dialog
    5. User submits form in dialog

    Anti forgery token is meant for user "" but the current user is "username"

    The reason this happens is because my application is 100% single-page, and when a user successfully logs in through an ajax post to /Account/JsonLogin, I simply switch out the current views with the "authenticated views" returned from the server but do not reload the page.

    I know this is the reason because if I simple reload the page between steps 3 and 4, there is no error.

    So it seems that @Html.AntiForgeryToken() in the loaded form still returns a token for the old user until the page is reloaded.

    How can I change @Html.AntiForgeryToken() to return a token for the new, authenticated user?

    I inject a new GenericalPrincipal with a custom IIdentity on every Application_AuthenticateRequest so by the time @Html.AntiForgeryToken() gets called HttpContext.Current.User.Identity is, in fact my custom Identity with IsAuthenticated property set to true and yet @Html.AntiForgeryToken still seems to render a token for the old user unless I do a page reload.

  • R. Schreurs
    R. Schreurs almost 11 years
    @parliament: you accepted this answer, could you share with us which option you chose?
  • Gone Coding
    Gone Coding over 10 years
    +1 for the nice & simple option 3. Timed logouts by OAuth providers also cause this problem.
  • Piotr Kula
    Piotr Kula about 10 years
    yea +1 for option 3. its really difficult to figure out where this happens on my site. Swithcing users or logging out causes this error but when I refresh its gone. Ehh. Thanks. This fixed it.
  • McGaz
    McGaz about 10 years
    Option 3 didn't work for me. Whilst logged out, I opened two windows onto the login page. Logged in as one user in one window, then logged in as another user in the other and received the same error.
  • xxbbcc
    xxbbcc about 10 years
    This is a terrible example of dealing with the problem in the question. Don't use this.
  • user3364244
    user3364244 about 10 years
    OK, use case: login form with anti forgery token. Open it in 2 browser tabs. Log in in first. You cant refresh second tab. What solution do you suggest to have correct behaviour for user who try to log in from second tab?
  • awright
    awright almost 10 years
    @McGaz -- good catch. Did you find a solution for this? Experiencing the same problem.
  • McGaz
    McGaz almost 10 years
    Unfortunately, I couldn't get a good solution to this. I removed the token from the login page. I still include it on posts after login.
  • Joao Leme
    Joao Leme almost 10 years
    Option 3 didn't work for me neither. Still getting same error.
  • Paul
    Paul over 9 years
    Option 3 did not work for me either. But option 2 worked perfectly well. I'm calling a $.get() on document load and reloading the token each time. The error only occurs for me on the login page. A user will log in, click back, and then login again. That was what was causing it for me.
  • wal
    wal over 9 years
    #3 should be removed from this answer. It doesnt disable the identiy check as implied. See asp.net/mvc/overview/security/… If this value is true, the system will assume that IIdentity.Name is appropriate for use as a unique per-user identifier and will not try to special-case IClaimsIdentity
  • dampee
    dampee over 9 years
    @user3364244: correct behaviour can the following: detect an external login by using websockets or signalR. This is the same session so you could make it work i guess :-)
  • Anshul Nigam
    Anshul Nigam over 9 years
    For option #3 Ms is saying that "Use caution when setting this value. Using it improperly can open security vulnerabilities in the application." msdn.microsoft.com/en-us/library/… So should we really use this?
  • Kaizer
    Kaizer over 8 years
    Number 2 was the one :) Cheers !
  • yourpublicdisplayname
    yourpublicdisplayname over 7 years
    My use case was the user tried a login, and got shown an error e.g. "account disabled" via ModelState.AddError(). Then if they clicked login again they would see this error. However, this fix just gave them a blank fresh login view again rather than the anti forgery token error. So, not a fix.
  • joe
    joe almost 7 years
    Option 2 worked for me. My code has to GET a new token, put that in __RequestVerificationToken, then POST.
  • Sam
    Sam over 6 years
    can anyone provide a sample code for option #2? I've tried option #3 and it doesn't work.
  • ransems
    ransems over 6 years
    Same, had option 3 in my solution, still getting error
  • DevEng
    DevEng about 6 years
    AntiForgeryConfig auto-complete does not give me an option to select SuppressIdentityHeuristicChecks. I'm using Asp .NET Web API
  • Jas
    Jas almost 6 years
    My Case : 1. User LogIn() and lands in the home page. 2. User hits back button and goes back to the Login view. 3. User login again and see the error "Anti forgery token is meant for user “” but the current user is “username”" On the error page If the user clicks on any other tabs from the menu, the application was working as expected. Using above code user can still hit back button but it gets redirected to the home page. So no matter how many time the user hits the back button it will redirect it to the home page. Thank you
  • Rajamohan Rajendran
    Rajamohan Rajendran over 5 years
    I am having same issue with Windows Authentication mode. System.Web.Mvc.HttpAntiForgeryException: 'The provided anti-forgery token was meant for user "Domain\User Name", but the current user is "User Name".'
  • Noobie3001
    Noobie3001 almost 5 years
    Any ideas why this doesn't work on a Xamarin webview?
  • stomy
    stomy almost 5 years
    For a full explanation see improving performance with output caching
  • Beingnin
    Beingnin almost 5 years
    AntiForgeryConfig.SuppressIdentityHeuristicChecks = true not working for me
  • Beingnin
    Beingnin almost 5 years
    @DevEng It is because that property is decorated with [EditorBrowsable(EditorBrowsableState.Never)] attribute. hence you cannot get that in autocomplete
  • Nicki
    Nicki over 4 years
    Excellent solution! This solved my issue after trying a lot of other suggestions that did not work. First off it was a pain reproducing the error, until I discovered that it could be because of 2 browsers or tabs open with the same page, and the user logging in from one, and then logging in from the second without reloading.
  • Steve Owen
    Steve Owen almost 4 years
    Thanks for this solution. Worked for me too. I added a check to see if the Identity was the same as the login username, and if so I happily continue trying to log the user in, and log them out if it's not. Eg, try { System.Web.Helpers.AntiForgery.Validate();} catch (HttpAntiForgeryException) { if (!User.Identity.IsAuthenticated || string.Compare(User.Identity.Name, model.Username) != 0) { // Your log off logic here } }
  • MikeTeeVee
    MikeTeeVee over 2 years
    Hope you don't mind, I used this answer and combined it with some other logic I found (to handle logging in as someone different) for answering an older question here: stackoverflow.com/a/68685999/555798 . Thanks for your help!