Skip to main content

Setting up Two-Factor Authentication in ASP.NET Core 2.0

In this article, I’m going to write bit about security aspects in ASP.Net Core 2.0.

Whenever you create a new ASP.NET Core application, you must notice that there is an option on dialog with a button captioned as Change Authentication and once you click on that, you will land upon a dialog having below 4 options as shown below:

  

I’ll discuss about each of these options in detail but as of now, to get started, let’s take a high-level idea about these
  • No Authentication – which means application is completely anonymous and open for everyone to access it.
  • Individual User Accounts – it uses local database for storing the information related to user.
  • Work or School Accounts – it means application will work with Office365, Active Directory, support for cloud, etc..
  • Windows Authentication – For internet application and uses IIS capabilities to know who has logged in.
Here I’ll be choosing my option as ‘Individual User Accounts’ which is very easy, simplest as well as common too, with sub option chosen as ‘Store user accounts in-app’.  
 
Once you clicked OK, you will notice that ASP.NET Core has added the required middleware in ConfigureServices method with a default token provider, as shown below:
  public void ConfigureServices(IServiceCollection services)
  {


            services.AddDbContext<ApplicationDbContext>(options =>

                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));



            services.AddIdentity<ApplicationUser, IdentityRole>()

                .AddEntityFrameworkStores<ApplicationDbContext>()

                .AddDefaultTokenProviders();


            services.AddMvc()

                .AddRazorPagesOptions(options =>

                {

                    options.Conventions.AuthorizeFolder("/Account/Manage");

                    options.Conventions.AuthorizePage("/Account/Logout");

                });



            services.AddSingleton<IEmailSender, EmailSender>();

   }
       
 
 
And in Configure method, same is added to the HTTP request pipeline by calling UseAuthentication method as shown below:
      
   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
   {

         if (env.IsDevelopment())
         {

             app.UseBrowserLink();
             app.UseDeveloperExceptionPage();
             app.UseDatabaseErrorPage();

          }
          else
          {
             app.UseExceptionHandler("/Error");
          }


          app.UseStaticFiles();


          

   app.UseAuthentication();

          app.UseMvc();


   }
 

Is middleware configuration sequencing matters?

One important thing to notice in above code snippet is the sequence in which middleware are configured. app.UserAuthentication is called after app.StaticFiles, which means we don’t want any of our static contents to be authenticated before rendering them on to the browser.

Are you thinking, why so? Well, let’s understand this with a most common example of Login page.
Login page, which usually has static contents like css, image, etc. If we will shuffle the sequence of both the statements, then Login page will never ever come until user is authenticated. Now if user is already authenticated, then why do we need Login page. Isn’t it an interesting analogy?

What happen on click of Register?

 Now quickly run the application and click on Register and register yourself as shown below:




















Once you populated the details and click on Register, you will land upon below page: 








Nothing to worry.

This is the expected behaviour because our identity data is not stored anywhere. So, we have to create the required tables and for that we can use local SQL Express database. This can be done quickly by pressing a button Apply Migrations as shown in above screenshot. Once button is pressed, just refresh your page and you would be happy to see the web page with your email id and Log out option in top right corner as shown below:
 




 

 

Configuring the registered data

Let’s say now if we want to modify our existing authentication details. So, to do that, one can click on mail id shown on top right corner of the web page and that will land upon below screen:
 

 

 

 

 

 

 

So, in above screen, we can change the registered email id, password and can also configure two-factor authentication.

Setting up two-factor authentication

Once you selected Two-factor authentication in above screen, you will be asked to add authenticator app as shown below:

 
 
 
 
 
 
 

Once the button is clicked, we will be taken to a page which will tell us that use the given key davi e4jo yiyt kmkz gtn5 jdek jmmb jpl5 as a password. Please note, this is the key generated for me. For you, it would be different one.
But typing this key manually in a phone could be very tedious process. Isn’t it?

So, other way to get the same information on phone is by using the QR code. You can also see a hyperlink which will take you to a very nice documentation explaining about the steps on how to proceed. 

Here we have to use JavaScript library for QR code generation. So, let’s quickly add that to our application under folder wwwroot/lib/qrCode.

Next is to call the method which will generate the QR code for us. Go to EnableAuthenticator.cshtml and update @section Scripts with below code:
 
       
    @section Scripts {


    @await Html.PartialAsync("_ValidationScriptsPartial")

    <script type="text/javascript" src="~/lib/qrCode/qrcode.js"></script>

    <script type="text/javascript">

     new QRCode(document.getElementById("qrCode"),
       {


                text: "@Html.Raw(Model.AuthenticatorUri)",


                width: 150,


                height: 150
       });


    </script>

}        

Make sure that path of qrcode.js is mentioned correctly. We are almost done. Now quickly launch the application and navigate back to Two-factor authentication tab. You will notice that nice QR code is ready for your scan as shown below:


Using Test Online Authenticator App

Now we have setup the two-factor authentication. In order to verify if it’s working correctly or not, we can use online authenticator app from URL: "https://gauth.apps.gbraad.nl/">https://gauth.apps.gbraad.nl/.

Steps to use this application are: 
Give some account name and give your key as a secret key and press Add. As soon as you will click on Add, some 6-digit number will be generated as shown below:
 
 










This 6-digit number we will use to verify our authentication as shown below:




 

Quickly click on Verify button and we are done with setting up our 2FA as shown below:
 









 

Using Recovery Codes

In previous screenshot, you must have seen that some numbers are displayed in red color. Those numbers are called recovery code which are very useful in case if you lose your phone or say you got a new phone. One should keep these keys in some secure place. Let’s have a look on how to use these recovery codes.
Launch your application and supply user name password. On supplying correct details, you will be asked for Authentication Key as shown below:
 















Now click on the given hyperlink ‘log in with recovery code.’ which will further ask you to enter your recovery code. Pick any one of the recovery keys which were generated for you and enter in the given text box as shown below:















As soon as you will click on Login button, you will see that you are logged in. Aren’t you happy, even after losing your phone 😉.
Now 2FA is perfectly set up, you can go and reset your recovery code anytime.

Please note, any recovery code which were generated can be use only once but one can generate recovery code any number of times.

Hope you enjoyed learning!

Comments