Anti-forgery token issue (MVC 5)

爱⌒轻易说出口 提交于 2019-11-28 02:58:31
Alex Filipovici

Try setting (in global.cs):

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

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
mzk

Just put this in global.asax.cs

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;

Try open link in incognito window or clear cookie from that domain(i.e. localhost).

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.

Kiran Chaudhari

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;
 } 
Ashu
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;

works for my case i am using ADFS Authentication.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!