22

I am creating a new User using ASP.NET Core Identity as follows:

new User {
  Email = "john@company.com",
  Name = "John"
}

await userManager.CreateAsync(user, "password");

I need to add a Claims when creating the user. I tried:

new User {
  Email = "john@company.com",
  Name = "John",
  Claims = new List<Claim> { /* Claims to be added */ }  
}

But Claims property is read only.

What is the best way to do this?

Evaldas Buinauskas
  • 12,532
  • 10
  • 45
  • 88
Miguel Moura
  • 28,129
  • 59
  • 187
  • 356

1 Answers1

43

You can use UserManager<YourUser>.AddClaimAsync method to add a claims to your user

var user = new User {
  Email = "john@company.com",
  Name = "John"
}

await userManager.CreateAsync(user, "password");

await userManager.AddClaimAsync(user, new System.Security.Claims.Claim("your-claim", "your-value"));

Or add claims to the user Claims collection

var user = new User {
  Email = "john@company.com",
  Name = "John"
}

user.Claims.Add(new IdentityUserClaim<string> 
{ 
    ClaimType="your-type", 
    ClaimValue="your-value" 
});

await userManager.CreateAsync(user);
agua from mars
  • 12,886
  • 4
  • 47
  • 56