Mahdi
Mahdi

Reputation: 768

can't remove user claim in asp Identity

i Try to update user claims in my service and at the first i should remove claims like this:

var userClaimCollection = this.AppUserManager.GetClaims(user.Id);
var toRemove = new List<Claim>();
foreach (var claim in userClaimCollection)
{
      if (claim.Type == group_role)
      {
           toRemove.Add(claim);                    
      }
}
foreach(var t in toRemove)
{
     Claim c = new Claim(group_role, t.Value);
     this.AppUserManager.RemoveClaim(user.Id, c);
}

but on RemoveClaim(user.Id,c) i get Collection was modified; enumeration operation may not execute error.
what really am i doing wrong?

Upvotes: 1

Views: 7692

Answers (3)

Pravin
Pravin

Reputation: 979

For deleting claims follow the steps given below,

Step 1: fetch the claims based on the User Id

   var claims = await manager.GetClaimsAsync(user.Id);

Step 2: Filter the needed claim from fetched claims.

var lastAccessedClaim = claims.FirstOrDefault(t => t.Type == claimType);

Step 3: Then, last use the removeclaim method to delete the claim for the user as shown below.

 var resDelete = (lastAccessedClaim == null)? null: await manager.RemoveClaimAsync(user.Id, lastAccessedClaim);

put the following code to get accurate result.

var claims = await manager.GetClaimsAsync(user.Id);
var lastAccessedClaim = claims.FirstOrDefault(t => t.Type == claimType);

var resDelete = (lastAccessedClaim == null)? null: await manager.RemoveClaimAsync(user.Id, lastAccessedClaim);

Upvotes: 2

Craig
Craig

Reputation: 11

I have a fix for this. Simply using 2.2.1 did not work for me. I wracked my brain on this as it seems like it should be easy to remove a claim. But the built in manager RemoveClaim utility would fail. I had a scenario where a claim was added twice. And I for the life of me I could not get rid of the duplicate claim entry.

until I iterated over indentity.claims and used TryRemoveClaim().

Example here:

    public async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

        foreach(Claim c in identity.Claims)
        {
            if (c.Type == "FullName" || c.Type == "AcctStatus")
            {
                identity.TryRemoveClaim(c);
            }
        }

        identity.AddClaim(new Claim("FullName", user.BF_FullName));
        identity.AddClaim(new Claim("AcctStatus", user.BF_AcctStatus));
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

Upvotes: 1

Mahdi
Mahdi

Reputation: 768

at the end i found my problem that was Identity 2.2.0 and after update to Identity 2.2.1 my problem solved.
i found my answer here

Upvotes: -2

Related Questions