MVC5 AntiForgeryToken Claims/“Sequence contains more than one element”

一笑奈何 提交于 2019-11-29 13:17:27
Adi Bilauca

The behavior is normal as you can see from the following method (called when creating the user identity):

await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)

in SignInAsync method. In the implementation of CreateIdentityAsync:

...         
ClaimsIdentity claimsIdentity = new ClaimsIdentity(authenticationType, this.UserNameClaimType, this.RoleClaimType);
claimsIdentity.AddClaim(new Claim(this.UserIdClaimType, user.Id, "http://www.w3.org/2001/XMLSchema#string"));
claimsIdentity.AddClaim(new Claim(this.UserNameClaimType, user.UserName, "http://www.w3.org/2001/XMLSchema#string"));
claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));
if (manager.SupportsUserRole)
{
    foreach (string rolesAsync in await manager.GetRolesAsync(user.Id))
    {
        claimsIdentity.AddClaim(new Claim(this.RoleClaimType, rolesAsync, "http://www.w3.org/2001/XMLSchema#string"));
    }
}
if (manager.SupportsUserClaim)
{
    claimsIdentity.AddClaims(await manager.GetClaimsAsync(user.Id));
}
...

As you can see there are three claims added by default. To them are added your "custom" claims. This is why you'll have duplicated claims, meaning that SingleOrDefault call on the claims collection will throw the error that you've mentioned. As a solution you can either use other claims either update them, after the identity creation, it's up to your business need.

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