Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add claims when creating a new user

Tags:

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

new User {   Email = "[email protected]",   Name = "John" }  await userManager.CreateAsync(user, "password"); 

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

new User {   Email = "[email protected]",   Name = "John",   Claims = new List<Claim> { /* Claims to be added */ }   } 

But Claims property is read only.

What is the best way to do this?

like image 226
Miguel Moura Avatar asked Sep 19 '16 16:09

Miguel Moura


People also ask

What is a user claim?

A claim is a statement that an entity (a user or another application) makes about itself, it's just a claim. For example a claim list can have the user's name, user's e-mail, user's age, user's authorization for an action. In role-based Security, a user presents the credentials directly to the application.

How can add additional claims in core identity in asp net?

Extend or add custom claims using IClaimsTransformationThe IClaimsTransformation interface can be used to add extra claims to the ClaimsPrincipal class. The interface requires a single method TransformAsync. This method might get called multiple times.

Where are user claims stored?

By default, a user's claims are stored in the authentication cookie.


1 Answers

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

var user = new User {   Email = "[email protected]",   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 = "[email protected]",   Name = "John" }  user.Claims.Add(new IdentityUserClaim<string>  {      ClaimType="your-type",      ClaimValue="your-value"  });  await userManager.CreateAsync(user); 
like image 61
agua from mars Avatar answered Sep 22 '22 16:09

agua from mars