Application authentication
.NET Core ASP.NET Core ASP.NET Core Identity C# Entity Framework Core OAuth Razor Visual Studio Web API

How to Customize User Identity in .NET Core Applications

Welcome to today’s post.

In a previous post I showed how to scaffold ASP.NET Identity functionality into an ASP.NET Core Web Application using Visual Studio 2017.

In today’s post I will extend this by showing you how to add additional fields to customize your user identity store for .NET Core applications and how to upgrade existing models, controllers and views to display and edit the new fields in the application.

In today’s post I will extend this by showing you how to add additional fields to customize your user identity store for .NET Core applications and how to upgrade existing models, controllers and views to display and edit the new fields in the application.

In the first section, I will explain what is included in the default user identity table.

The Default User Identity

The scaffolded version of the identity store has default fields used for the user identity table in the generated ASP.NET Core identity database. These are sufficient for many ASP.NET Core Identity applications.

The default identity table is named IdentityUser.

The default user identity that is generated for you using the built-in Identity scaffold project in Visual Studio 2017 has some basic fields.

These include:

  • UserName
  • Email
  • ContactNumber
  • PhoneNumber
  • NormalizedEmail
  • NormalizedUserName
  • SecurityStampPasswordHash

To use an identity table with custom fields in our application, we will need to override the IdentityUser class from ASP.NET Core Identity library and include the new fields in the overridden class. I will show how this is done in the next section.

Adding Custom Fields to the User Identity Table

If we wish to include additional fields for first name, last name, and date of birth we can add these fields into the ApplicationUser model, which overrides the IdentityUser class as shown:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace BookLoan.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DOB { get; set; }
    }
}

Note: The [PersonalData] data attribute is available from .NET Core 2.1 onwards.

Next, we will apply the migration to the database. The PowerShell scripts below require the inclusion of the Entity Framework Core NuGet package in our application.

Open the PowerShell console.

Run the migration command to generate the migration script.

For example:

Add-Migration add_useridentity_newfields_09_12_2019

To commit the migration to the identity database, we use the command:

Update-Migration

We then check if the new fields have been added successfully by opening SSMS or the table through the Object Explorer.

In the next two sections, I will show how to update any model and controller classes to use the user identity object with the custom fields.

Including Custom Identity Fields to Model Classes

In this section I will show how to update existing model classes to use the custom fields in our revised user identity table.

The models I use for viewing user details and registering users is shown below:

\Models\ManageUserViewModel\UserViewModel.cs,

\Models\ManageViewModel\IndexViewModel.cs,

\Models\AccountViewModels\RegisterViewModel.cs,

The controllers I use for managing user details and user accounts is shown below:

\Controller\ManageController.cs

\Controller\AccountController.cs

The views I use for managing users and registering user accounts is shown below:

\Manage\Index.cshtml

\Account\Register.cshtml

The model class change with the custom fields are shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BookLoan.Models.ManageUserViewModels
{
    public class UserViewModel
    {
        public string ID { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
	    // custom personal fields
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DOB { get; set; }
    }
}

The model change for displaying editable user details is shown below:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace BookLoan.Models.ManageViewModels
{
    public class IndexViewModel
    {
        public string Username { get; set; }

        public bool IsEmailConfirmed { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Phone]
        [Display(Name = "Phone number")]
        public string PhoneNumber { get; set; }

        public string StatusMessage { get; set; }

        // custom personal fields
        public string FirstName { get; set; }

        public string LastName { get; set; }

        [DataType(DataType.Date)]
        public DateTime DOB { get; set; }
    }
}

In the next section, I will show how to access the custom fields added to our models within controller classes.

Accessing Custom Fields from Controller Classes

In this section I will show how to update existing controller classes to use the custom fields in our revised model classes.

The Index controller class, which has HTTP GET and POST methods will be modified to support the changes to the models we modified in the previous section.

In Index.cs, the change for the GET method is below:

[HttpGet]
public async Task<IActionResult> Index()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
    }
    var model = new IndexViewModel
    {
        Username = user.UserName,
        Email = user.Email,
        PhoneNumber = user.PhoneNumber,
        FirstName = user.FirstName,
        LastName = user.LastName,
        DOB = user.DOB,		  
        IsEmailConfirmed = user.EmailConfirmed,
        StatusMessage = StatusMessage
    };
    return View(model);
}

In your POST controller, call to update the user data using:

await _userManager.UpdateAsync(user);

is required.

For changes to AccountController.cs, changes to the Register() get and post methods are required.

For changes to the Index.cshtml profile update and Register.cshtml profile creation add the markup:

<div class="form-group">
   <label asp-for="FirstName"></label>
      <input asp-for="FirstName" class="form-control" />
</div>

<div class="form-group">
   <label asp-for="LastName"></label>
   <input asp-for="LastName" class="form-control" />
</div>

<div class="form-group">
   <label asp-for="DOB"></label>
   <input asp-for="DOB" class="form-control" />
</div>

After all these changes have been applied and the application built, then test the registration, update profile and login functions.

Now open SSMS and query the database for the newly created user and registration data:

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT TOP (1000) [Id]
      ,[UserName]
      ,[DOB]
      ,[FirstName]
      ,[LastName]
FROM [AspNetUsers]

Test also the manage user profile and update a property from one of the custom fields:

Now check the data by query:

If the update is successful, then the new fields will be modified.

The above overview has shown us how to add custom fields to a user identity table, apply the changes to the underlying SQL identity store database schema using Entity Framework Core, then update the corresponding model and controller classes in our code.

That’s all for today!

I hope you learnt something useful.

In a future post I will be applying our data to help us with claims-based authentication and authorizations.

Social media & sharing icons powered by UltimatelySocial