Login Module Included: Authentication Using ASP.Net Core 2.1 Identity

After spending a solid 4 hours getting requirements for a Web App, I was asked this question in a very nonchalant way. There are no two answers to it, Authentication has become a very basic feature, so basic, that every client assumes that it will be included in the “package.” They don’t expect to spend extra money or carve out any additional development time for it.

It is needless to say that this Login module should offer all the basic features like password hashing, reset password, forgot password, two-factor authentication, login using external providers such as Facebook, Google, etc.

In all honesty, this expectation is not far-fetched. All the decent websites out there offer these basic features for a Login module and so it is not out of ordinary to expect to see them it in your newly built, modern, Web App.

If only there was a switch that would let developers include Login module, oh wait … there is!!!

With minimal coding and options for Scaffolding, developers can now get Authentication modules up and running in considerably less amount of time. In my blog, I am going to describe how you can implement Authentication using latest ASP.Net Core framework 2.1.

DIY Login Module

If, for whatever reason, I decided to implement the Login Module from scratch it wouldn’t be the wisest move, but it’s possible. I would start by creating a User table that stores mainly username and password, carefully hashing the password. This table will also save some User specific Data like First name, Last name, etc. Then I would write logic for Login that authenticates if the entered username and password is a match. Login will also be responsible for maintaining a session/cookie at the client side which will be passed with every request suggesting that the user is logged in. Logout will wipe out this cookie.

This is a simple, Plain Jane Login Module, and we haven’t even scratched the surface yet. Password reset, forgot Password, two-factor authentication, Login with Google, Facebook, etc., role-based and claims-based authorization, token-based authorization. Implementing all these from scratch would be a considerable sized project in itself.

ASP.Net offers out of the box, ready to use login solutions called ASP.Net Core IDENTITY.

ASP.Net Core 2.1 Identity

ASP.Net Core 2.1 Identity is a membership system that provides Login functionality. Two main things are facilitated by this system.

Code wrapped in libraries that would perform all the functions expected of a Login Module. Such as Login/Logout, Password reset, forgot Password, Two-factor authentication, Login with Google, Facebook, etc., role-based and claims based authorization, token-based authorization.

Sample Web App with Authentication

Using Visual Studio 2017, I am going to demonstrate how you can include Authentication with a single step.

Test Login Module

If you try to register, then you will come across a page that looks like this. Click Apply Migration.

At this point, you will have an out of the box, completely functioning Login Module. Tada!

Great, so we got this working, but how exactly??

Q) Where is the Identity database? Who created it?

A) Migrations

In our DIY Login Module, we said that we will need a data store to save usernames, passwords and profile. So, let’s look at our appsettings.json (web.config equivalent) for a connection string.

Aha, so apparently a new database aspnet-AuthUsingIdentity-650B89DE-10F8-4596-9CED-F24F1B53EFC2 was created for me by the wizard when I clicked “Apply Migrations.” Here is the database with Authentication tables.

Let’s understand Migrations

To understand Migrations, we first must understand ORM and Code First.

In ORM (Object Relational Mapping), every database table has a corresponding class that represents it as an object. e.g. dbo.AspNetUsers table will have a class in the code that maps to this table. And all the records in this table will be instances of that class.

Code First is a technique which helps us to create and maintain databases and its tables from the code. So instead of starting from creating a table called dbo.AspNetUsers, we will first write the code for Class dbo.AspNetUsers and then tell Entity Framework to go and create a table for us.

Migrations in EF Core allow this magic to happen. It automatically creates code that will create the database when run for the first time, and from there on it will create incremental scripts to keep the code and database in sync.

So, when we clicked Apply Migrations button, what happened behind the scenes was that a Migration was added and executed, and 3 new files were created under the Migrations folder.

Alternatively, you can also run the Migration in Visual Studio Package Manager Console using PowerShell Command.

Add-Migration <migration-name>

Tip:

If you don’t want your database to be called some weird long name like aspnet-AuthUsingIdentity-650B89DE-10F8-4596-9CED-F24F1B53EFC2 then before applying the Migrations, change the connection string in appsettings.json.

Q) Where is the UI/Views for Login/Logout?

A) Razor Class Library (RCL)

While testing the Sample App, we saw Login and Register pages/views but when you try to locate them in the code there is nothing under Areas -> Identity folder. The mystery behind this is that all the Identity Code is neatly wrapped in a Razor Class Library. The objective behind this is that the user need not see the clutter of Razor Views, Pages, Controllers, Data Models used by Identity.

Razor Class Libraries can be thought of as Class Libraries but with Views, Pages, Controllers, Data Models, etc. This bundle can be reused and included in applications. Applications can also override the Views and Pages it contains. When a view, partial view, or Razor Page is found in both the web app and the RCL, the Razor markup (.cshtml file) in the web app takes precedence.

Let’s Understand Scaffolding

Although the Identity code is hidden in a Razor Class Library, we can still get access to all of it or we can selectively pick a few files to override. Scaffolding (how I see it) is resurrecting the code from dust.

And this is how Scaffolding is done using Visual Studio 2017.

From Solution Explorer, right-click on the project > Add > New Scaffolded Item.

From the left pane of the Add Scaffold dialog, select Identity > ADD.

In the ADD Identity dialog, select the options you want.

Customize Identity

ASP.Net Core 2.1 Identity can be configured and customized to suit your business needs. Here are a few popular customizations and how to go about them:

Password policy, lockout, cookie configuration, Sign-In Options

These get the default settings but can be easily overridden in the Startup class.

Add custom user data

e.g. Add First and Last Name to the User Registration Page

For this you will first run Scaffolding to get the Views, Models, to override. Add new Properties to the Model, update Views, run Migration to add new columns to the database User Table.

So, to answer the very first question ‘It comes with a Login module, right? Answer to this is a loud and clear ‘Yes, it does!’