Adding Identity to a web app
Follow the steps in Freeman, Ch. 28 through the end of "Setting up
the User Classes", but skip "Creating a Controller and View"
- Modify your application's DbContext class to inherit from
- All you need to do is change the inheritance
- Don't add a new DbSet for Identity, that will be done by the
- In Startup.cs, ConfigureServices, add:
- The AddIdentity method has generic type specifiers for my
user class and thethe built-in IdentityRole class for roles.
- The AddEntityFrameworkStores method specifies that Identity should use Entity
Framework Core to store and retrieve its data, using the application's database context class.
AddDefaultTokenProviders method uses the default configuration to support operations that require a
token, such as changing a password.
- In Startup.cs, Configure, add:
- Modify your user model so that the class inherits from
The IdentityUser has these properties:
- Id - This property contains the unique ID for the user.
- UserName - This property returns the user’s username.
- Claims - This property returns the collection of claims for
the user, which I describe in Chapter 30.
- Email - This property contains the user’s e-mail address.
- Logins - This property returns a collection of logins for
the user, which is used for third-party authentication, as
described in Chapter 30.
- PasswordHash - This property returns a hashed form of the
user password, which I use in the “Implementing the Edit
- Roles - This property returns the collection of roles that
the user belongs to, which I describe in Chapter 29.
- PhoneNumber - This property returns the user’s phone number.
- SecurityStamp - This property returns a value that is
changed when the user identity is altered, such as by a password
- Add a migration for the new user model and update the
After adding Identity to your project, Inspect the database using SQL
Server Object Explorer and note the new tables added by Identity. The
tables listed below should have been created.
This is your user table, it contains the
fields you added in your user class.
- Using Identity in administrative pages
Add an admin controller and views:
- Create a user account
- Show all user accounts
- Delete a user account