Home Customize Asp.Net Core’s IdentityUser
Post
Cancel

Customize Asp.Net Core’s IdentityUser

Alt text

In the last post we set up the Asp.Net Identity database and saw that our tables were all created for us. There is a lot of fields in the AspNetUsers table but if we do a bit of forshadowing….we know that we will need some extra fields.

I would like to show the user’s name when they are logged in so I think I want to add a FirstName and LastName field to the AspNetUsers table. I also want to add an IsActive flag to the user for those cases where I don’t want the user to access the system any longer but do not want to remove the user record in the database.

Let’s start by adding a new ApothecaricUser class to our project.

Alt text

Our ApothecaricUser needs to inherit from IdentityUser to gain all the benefit from the Asp.Net Identity functionality. In this class, we just add our new fields. I have also added some DataAnnotations to set the field length when the database creates our new fields.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;

namespace ApothecaricApi.Models.Identity
{
  public class ApothecaricUser : IdentityUser
  {
    [StringLength(250)]
    public string FirstName { get; set; }

    [StringLength(250)]
    public string LastName { get; set; }

    public bool IsActive { get; set; }
  }
}

After we have our user class created, we need to revisit our custom Db Context (ApothecaricDbContext). Here we need to add our new user class (ApothecaricUser) to as a type injected into the IdentityDbContext that we are inheriting from.

1
2
3
4
5
6
7
8
9
10
11
using ApothecaricApi.Models.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace ApothecaricApi.Data
{
  public class ApothecaricDbContext : IdentityDbContext<ApothecaricUser>
  {
    public ApothecaricDbContext(DbContextOptions options) : base(options) { }
  }
}

Now, we can run another Migration and push this change to our database. Bring up the Nuget Package Manager Console again. I will name this Migration “2 Custom_App_User”.

1
PM> Add-Migration "2 Custom_App_User"

And after we run “Update-Database” and look at the AspNetUsers table,we can see that our new fields have been added to the user table and is ready for our use.

Alt text

The next post, we will look at adding one more piece to this table and adding a whole new table to the Asp.Net Identity fold. We will add a Tenant table to assist in having our new API able to handle Multi-Tenancy. We will have to tie our Users to a Tenant so the AspNetUsers and our ApothecaricUser class will both need a little foreign key addition.

Hope to see you then!

This post is licensed under CC BY 4.0 by the author.