How to Extend IdentityUser with a Custom Property

I am using asp.net Identity 2.0 to login to my site where authentication data is stored in an SQL database. Asp.net authentication was implemented in a standard way, as can be found in many online tutorials.

The ApplicationUser class in IdentityModels been extended to include a custom property:

 public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) { CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); return userIdentity; } //My extended property public string Code { get; set; } } 

When I register a new user, I pass the Code custom property to RegisterBindingModel , but I'm not sure how to insert this custom property into the WebUsers table.

I did this below, but in fact it does not insert this property into the table along with the username and password.

 var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code }; 

And the whole function:

 [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var userName = !string.IsNullOrEmpty(model.UserName) ? model.UserName : model.Email; //I set it here but it doesn't get inserted to the table. var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } 

What am I missing? I looked at similar questions, but could not find an answer for this.

+22
source share
3 answers

If you complete all the steps to add a custom field for a user, you will complete the task successfully.

Here are all the steps to add a custom field for the user:

  1. Build an ASP.NET Web Application
  2. Make sure you select MVC and authentication is individual user accounts
  3. Go to the Models folder → Open IdentityModels.cs → ApplicationUser class and add the property:

     public string Code { get; set; } 
  4. Build a project
  5. Go to TOOLS menu → Nuget Package Manager → click Package Manager Console
  6. Type Enable-Migrations , press Enter and wait for the task to complete. You will see an answer that reads:

      Checking if the context targets an existing database... Code First Migrations enabled for project WebApplication1. 
  7. Type Add-Migration "Code" , press Enter and wait for the task to complete. You will see an answer that reads:

     Scaffolding migration 'Code'. The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Code' again. 
  8. Type Update-Database , press Enter and wait for the task to complete. You will see an answer that reads:

     Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Applying explicit migrations: [201611132135242_Code]. Applying explicit migration: 201611132135242_Code. Running Seed method. 

    At this point, if you update the SQL Server Object Explorer and go to the database and see the tables, in the dbo.AspNetUsers section in the columns you will see the Code field. If you did not know which database or even which server you should look for, open the Web.Config file and see the connection string, which looks something like this:

     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20161114125903.mdf;Initial Catalog=aspnet-WebApplication1-20161114125903;Integrated Security=True" providerName="System.Data.SqlClient" /> 

    You can see the data source (which is the sql server instance) and something .mdf, which is the database name.

  9. Go to the Models folder → Open the AccountViewModels.cs file → RegisterViewModel class and add this property: (In APIv2 with EF6 you can add the following line to the Models folder → AccountBindingModels file → RegisterBindingModel class)

     public string Code { get; set; } 
  10. Go to the “Views” folder → “Account folder” → open the Register.cshtml file and add this code next to other fields, for example, with a password:

     <div class="form-group"> @Html.LabelFor(m => m.Code, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.Code, new { @class = "form-control" }) </div> </div> 
  11. Go to the “Controllers” folder → Open the AccountController.cs file → in the “Register http” action, change the line in which the user is created:

     var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Code= model.Code }; 
  12. Run the project and follow the link /Account/Register and register a new user. After user registration, if you go back to the database and view the data in the dbo.AspNetUsers table, you will see that the code has been saved.

Download

You can clone or download a working example here:

More info: how to add my own property to IdentityRole?

If you're interested in learning how to add a new property to IdentityRole , see How do I add my own property to IdentityRole?

+58
source

Hope this can help others, as the original post is 1+ years old

If you have already created a project with "Authentication of individual user accounts:

In Solution Explorer, go to project> Models> IdentityModels.cs

under the public class ApplicationUser: IdentityUser (should be the first class).

Add your custom properties after the public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) as in my example below:

 public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } **//add custom properties here - these are just examples** public bool SendEmails { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } 

Then using the NuGet Packagemanager:

  • enable-migrations (if you have not already done so)
  • add migration [input]
  • nameYourMigration [enter]
  • (view the migration file to make sure your properties are added)
  • Database update [enter]
  • Check the AspNetUsers database table to verify that the properties have been added correctly.

Hope this helps ..

+6
source

I think the main problem is still that you are not registering new applications in the ApplicationUser class.

I had the same problem and solved it in a few lines after CreateIdentityAsync .

 public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) { CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here userIdentity.AddClaim(new Claim("Code",this.Code)); return userIdentity; } //My extended property public string Code { get; set; } } 
0
source

Source: https://habr.com/ru/post/1012228/


All Articles