ASP.NET Core - Two Factor Authentication Using Google Authenticator

Introduction

In this article, we are going to learn how to perform two-factor authentication in an ASP.NET Core application using Google Authenticator app. The user needs to configure the Google Authenticator app on his/her smartphone using the QR code generated in the web app. At the time of logging in to the web application, a user has to enter a six-digit pin that will be generated in the app to finish two-factor authentication. The key generated in the app will be unique to the userid and is a time-based one-time password (TOTP); i.e., it will expire after a certain time.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.

Create MVC Web Application

Open Visual Studio and select File >> New >> Project. After selecting the project, a "New Project" dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as TwoFactAuth and press OK. 

After clicking OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these drop-downs. Then, select “Web application (Model-View-Controller)” template. Click on "Change Authentication" button; a "Change Authentication" dialog box will open. Select “Individual User Account” and click OK. Now, click OK again to create our web app.

 

Adding QR Codes to configure two-factor authentication

We will be using QR code to configure and sync Google authenticator app with our web app. Download qrcode.js JavaScript library from https://davidshimjs.github.io/qrcodejs/ and put it into wwwroot\lib folder of your application. Now, your wwwroot folder will have the following structure.

 

Open Views\Manage\EnableAuthenticator.cshtml file. You will find @section Scripts at the end of the file. Put the following code in it.

  1. @section Scripts {  
  2.     @await Html.PartialAsync("_ValidationScriptsPartial")  
  3.     <script src="~/lib/qrcodejs/qrcode.js"></script>  
  4.     <script type="text/javascript">  
  5.         new QRCode(document.getElementById("qrCode"),  
  6.             {  
  7.                 text: "@Html.Raw(Model.AuthenticatorUri)",  
  8.                 width: 200,  
  9.                 height: 200  
  10.             });  
  11.     </script>  
  12. }  

This EnableAuthenticator.cshtml file already have a div with id “qrCode” (see line 25 in below code). We are generating a QR code inside that div using qrcode.js library. We are also defining the dimensions of the QR code in form of width and height.

So finally, your EnableAuthenticator.cshtml file will look like this.

  1. @model EnableAuthenticatorViewModel  
  2. @{  
  3.     ViewData["Title"] = "Enable authenticator";  
  4.     ViewData.AddActivePage(ManageNavPages.TwoFactorAuthentication);  
  5. }  
  6.   
  7. <h4>@ViewData["Title"]</h4>  
  8. <div>  
  9.     <p>To use an authenticator app go through the following steps:</p>  
  10.     <ol class="list">  
  11.         <li>  
  12.             <p>  
  13.                 Download a two-factor authenticator app like Microsoft Authenticator for  
  14.                 <a href="https://go.microsoft.com/fwlink/?Linkid=825071">Windows Phone</a>,  
  15.                 <a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and  
  16.                 <a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or  
  17.                 Google Authenticator for  
  18.                 <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en">Android</a> and  
  19.                 <a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>.  
  20.             </p>  
  21.         </li>  
  22.         <li>  
  23.             <p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p>  
  24.             <div class="alert alert-info">To enable QR code generation please read our <a href="https://go.microsoft.com/fwlink/?Linkid=852423">documentation</a>.</div>  
  25.             <div id="qrCode"></div>  
  26.             <div id="qrCodeData" data-url="@Model.AuthenticatorUri"></div>  
  27.         </li>  
  28.         <li>  
  29.             <p>  
  30.                 Once you have scanned the QR code or input the key above, your two factor authentication app will provide you  
  31.                 with a unique code. Enter the code in the confirmation box below.  
  32.             </p>  
  33.             <div class="row">  
  34.                 <div class="col-md-6">  
  35.                     <form method="post">  
  36.                         <div class="form-group">  
  37.                             <label asp-for="Code" class="control-label">Verification Code</label>  
  38.                             <input asp-for="Code" class="form-control" autocomplete="off" />  
  39.                             <span asp-validation-for="Code" class="text-danger"></span>  
  40.                         </div>  
  41.                         <button type="submit" class="btn btn-default">Verify</button>  
  42.                         <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  43.                     </form>  
  44.                 </div>  
  45.             </div>  
  46.         </li>  
  47.     </ol>  
  48. </div>  
  49. @section Scripts {  
  50.     @await Html.PartialAsync("_ValidationScriptsPartial")  
  51.     <script src="~/lib/qrcodejs/qrcode.js"></script>  
  52.     <script type="text/javascript">  
  53.         new QRCode(document.getElementById("qrCode"),  
  54.             {  
  55.                 text: "@Html.Raw(Model.AuthenticatorUri)",  
  56.                 width: 200,  
  57.                 height: 200  
  58.             });  
  59.     </script>  
  60. }  

When we execute the program, a QR code will be generated in this View and the user can set up two factor authentication using the Google authenticator with the help of this QR code.

Configure two-factor authentication

Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console. It will open the Package Manager Console. Put in Update-Database command and hit Enter. This will update the database using Entity Framework Code First Migrations.

 

Press F5 to launch the application and click on Register in the top right corner of the homepage. You can see a user registration page. Fill in the details and click on Register button as shown in the image below.

 

Upon successful registration, you will be logged into the application and navigated to the home page. Here, you can see your registered Email id at the top right corner of the page. Click on it to navigate to “Manage your account” page. Select TwoFactorAuthentication from the left menu. You can see a page similar to that shown below.

 

Click on Configure authenticator app button. You can see a QR code generated on your screen and it is asking for a Verification Code also as shown in the image below.

 

You need to install Google Authenticator app on your smartphone to scan this QR code in order to generate a Verification Code and complete two-factor authentication setup. Download and install Google authenticator for Android from Play Store and for iOS from App Store. I am using an Android device for this demo.

Launch the app on your smartphone. You can see the welcome screen as shown in the image below.

 
 
Click on "Begin". It will ask you to add an account by providing two options -
  1. Scan a barcode
  2. Enter a provided key 

Click on “Scan a barcode” and scan the QR code generated by the web app. This will add a new account to Google authenticator and generate a six-digit pin on your mobile screen. This is our two-factor authentication code. This is a TOTP ( time-based one-time password). You can observe that it keeps on changing frequently (life span of 30 seconds). 

Here you can also see the application name as well as your registered email id in the app as shown below. 
 

Put this pin in the Verification Code textbox and click on verify. Upon successful verification, you will see a screen similar to the one shown below. This will give you the recovery codes for your account that will help to recover your account in case you are locked out. Take a note of these codes and keep it safe with you.

 

And thus, the two-factor authentication setup is complete. Let’s check if our two-factor authentication is working correctly or not.

Logout of the application and click on login again. Enter your registered email id and password and click on login.

 
 
Now you can see a the two-factor authentication screen asking for Authenticator code. Put in the code that is generated currently in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page.
 
 

If you check “Remember this machine” option then it will not ask for Authenticator code on the same machine again. You can skip the two-factor authentication in this case.

Conclusion

We have successfully generated QR code using qrcode.js JavaScript library and used it to configure Google Authenticator app. This app will generate a six-digit TOTP which the user needs to enter while login into the web application, thus implementing two-factor authentication in a ASP.NET Core application.

Please refer to the attached code for better understanding.

See Also