Adding identity management entities to your data model

When working with user identities, your database and applications data model usually contain entities such as User, Roles, Claims, Tokens, and so on, so the first step will be to add the necessary entities to the application data model, but luckily we don't need to add them manually. Instead, the Microsoft.Extensions.Identity infrastructure defines base classes that we can use. Here are the steps that you need to perform to add all the identity-related entities to your application:

  1. Create or modify the User entity in your application and make it derive from the IdentityUser class. Note that if you already have a User entity, you have to remove the primary key property because IdentityUser already contains it within the name Id.
  2. Modify your application's DbContext to derive from IdentityDbContext<User>. Note that if you had a property with the name Users, you'll need to remove it because IdentityDbContext already defines it.
  3. Create a new migration (as explained in Chapter 5, Persisting Data with Entity Framework).

Run the application and make sure that the migration is completed successfully, then review the database in the Server Object Explorer (SQL). You should see a few tables that were added, all prefixed with AspNet:

The IdentityUser base class brings a few properties that are used by the identity management infrastructure. However, you can add any properties you want to the derived class.

Now, you have the necessary data entities in your application, and though possible, it's not recommended that you work with them directly and insert, update, delete, or query them directly. The recommended approach is that you use the types that are provided with the identity infrastructure, such as UserManger, SignInManager, and others to get access to the operations you want to perform. To allow for the usage of those types, we first need to make our ASP.NET Core application aware of them and enable the identity infrastructure capabilities. Afterwards, I will show how you how to register users, sign them in, and query them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.35.194