简体   繁体   中英

Trouble with antiforgery token using owin

I'm setting OWIN authentication with my app but I have one problem. I set the validate and anti-forgery token on my login page and when I make a POST all works fine, but on another page setting the validate and anti-forgery token when I make a POST causes the following error to appear:

Anti-forgery token provider was designed for user "user@domain.com" but the current user is "" ...

So how I can fix this without using AntiForgeryConfig.SuppressIdentityHeuristicCheck in Global.asax?

Why doesn't the anti-forgery token take the current user?

UPDATE

The Task<ClaimsIdentity> implements like this:

public override Task<ClaimsIdentity> CreateIdentityAsync(AppUser user, string authenticationType)
    {
        return Task<ClaimsIdentity>.Factory.StartNew(() =>
        {
            var claimsList = new List<Claim>()
            {   
                new Claim(ClaimTypes.Name, user.Email),                                        
            };

            return new ClaimsIdentity(authenticationType);
        });
    }

And the Task SignInAsync like this:

public override async Task SignInAsync(AppUser user, bool isPersistent, bool rememberBrowser)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }        

The user.Email is user@domain.com

If the user is logged on then anti forgery token will be issued for that user. Let me give you an example:

  1. Say you have two pages with anti forgery token that submit with form data: Login Page and Search Page

  2. Open search page and perform a search, it will be fine.

  3. Now open login page on another tab (in browser) and login successfully.

  4. Now go back to search page that is already open in the previous tab. Try to perform a search and boooom, you will get anti forgery token error.

  5. Now re-fresh the search page and do another search, it will be fine.

It is because initially the token on search page didn't have user info but the server expects it because the user is logged on. On re-fresh of the search page token gets updated with logged on user info, so it throws no error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM