Anti-forgery token issue (MVC 5)

前端 未结 7 1841
长发绾君心
长发绾君心 2020-12-07 09:15

I am having an issue with the anti-forgery token :( I have created my own User class which worked fine but now I am getting an error whenever I go to the /Account/Re

相关标签:
7条回答
  • 2020-12-07 10:01

    Do you know what claims you do get in your ClaimsIdentity? If not:

    1. Remove the [ValidateAntiForgeryToken] attribute
    2. Put a breakpoint somewhere in your controller and break at it
    3. Then look at the current ClaimsIdentity and examine the claims
    4. Find one that you think will uniquely identify your user
    5. Set the AntiForgeryConfig.UniqueClaimTypeIdentifier to that claim type
    6. Put back the [ValidateAntiForgeryToken] attribute
    0 讨论(0)
  • 2020-12-07 10:02

    Try setting (in global.cs):

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
    
    0 讨论(0)
  • 2020-12-07 10:05

    Edit: Having a greater understanding of this problem at this moment, you can disregard my answer below.

    Setting AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; in Application_Start() of Global.asax.cs fixed it for me. Even though I have the claim http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier set, I get the same error as in the original question. But pointing it out as above somehow works.



    Starting with MVC4 the anti-forgery-token doesn't use User.Identity.Name as the unique identifier. Instead it looks for the two claims given in the error message.

    Update NOTE: This should not be needed You can add the missing claims to your ClaimsIdentity when the user is being logged in, like so:

    string userId = TODO;
    var identity = System.Web.HttpContext.Current.User.Identity as ClaimsIdentity;
    identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", userId));
    identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId));
    

    Note that one of the claims might already be there from before, and you will get an error with duplicate claims if you add both. If so, just add the one missing.

    0 讨论(0)
  • 2020-12-07 10:08
    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
    

    works for my case i am using ADFS Authentication.

    0 讨论(0)
  • 2020-12-07 10:13

    Just put this in global.asax.cs

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
    
    0 讨论(0)
  • 2020-12-07 10:16

    In Global.asax.cs,

    1.Add these namespaces

    using System.Web.Helpers;
    using System.Security.Claims;
    

    2.Add this line in method Application_Start:

     protected void Application_Start()
     {
           .......
           AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
     } 
    
    0 讨论(0)
提交回复
热议问题