Google Authenticator In ASP.NET

Introduction

 
In this blog, I am going to teach you how to implement 2FA authentication in your ASP.NET web application using Google Authenticator app. We need to install the Google Authenticator app on our mobile phone from the respective play store or app store, and using the QR code generated in the web application we will verify the user. When a user signs in to the web application, they need to enter a six-digit passcode that will be generated in the mobile app to finish two-factor authentication process. The passcode generated in the mobile app will be unique to the UserIdentifier and is a time-based one-time password (TOTP); i.e., it will expire after a certain interval of time.
 
Prerequisites
  • Install the latest version of Visual Studio 2019 Community Edition from here.
  • Install the Google authenticator app from Google Play Store/Apple App Store/Windows App Store

Steps for setup two-factor authentication in ASP.NET

 
Step 1
 
Create new empty project in ASP.NET
 
Step 2
 
Add the Webform name as Authenticator.aspx
 
Step 3
 
Then install the Google.Authenticator library from Nuget.
 
Step 4
 
Copy & paste the below mention designer & code behind file.
 
Step 5
 
Rebuild the solution and hit F5
 
Authenticator Designer Code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Authenticator.aspx.cs" Inherits="_2Fa_4_5_1.Authenticator" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.         <div class="container">  
  13.             <div class="jumbotron">  
  14.                 <h2 class="text-info text-center">Google Authenticator</h2>  
  15.                 <hr />  
  16.                 <div class="row">  
  17.                     <div class="col-md-12">  
  18.                         <div class="section">  
  19.                             <h3 class="text-info">Step 1: Install Google Authenticator  
  20.                             </h3>  
  21.                             <p>Please download and install Google Authenticator on your IPhone/IPad/Android device, if already not installed.</p>  
  22.                         </div>  
  23.                     </div>  
  24.                     <div class="col-md-12">  
  25.                         <div class="section">  
  26.                             <h3 class="text-info">Step 2: Link your device to your account:  
  27.                             </h3>  
  28.                             <p>You have two options to link your device to your account:</p>  
  29.                             <p><b>Using QR Code:</b> Select<b> Scan a barcode</b>. If the Authenticator app cannot locate a barcode scanner app on your mobile device, you might be prompted to download and install one. If you want to install a barcode scanner app so you can complete the setup process, select Install, then go through the installation process. Once the app is installed, reopen Google Authenticator, then point your camera at the QR code on your computer screen.</p>  
  30.                                
  31.                     <p>  
  32.                         <b>Using Secret Key:</b>  
  33.                         Select <b>Enter provided key</b>, then enter account name of your account in the <b>"Enter account name"</b> box. Next, enter the secret key appear on your computer screen in the <b>"Enter your key"</b> box. Make sure you've chosen to make the key Time based, then select Add.  
  34.                     </p>  
  35.                         </div>  
  36.                     </div>  
  37.                     <div class="col-md-12">  
  38.                         <div class="col-md-4">  
  39.                             <asp:Image ID="imgQrCode" runat="server" />  
  40.                         </div>  
  41.                         <div class="col-md-6">  
  42.                             <div>  
  43.                                 <span style="font-weight: bold; font-size: 14px;">Account Name:</span>  
  44.                             </div>  
  45.                             <div>  
  46.                                 <asp:Label runat="server" ID="lblAccountName"></asp:Label>  
  47.                             </div>  
  48.                                
  49.                         <div>  
  50.                             <span style="font-weight: bold; font-size: 14px;">Secret Key:</span>  
  51.                         </div>  
  52.                             <div>  
  53.                                 <asp:Label runat="server" ID="lblManualSetupCode"></asp:Label>  
  54.                             </div>  
  55.                         </div>  
  56.                     </div>  
  57.                     <div class="clearfix"></div>  
  58.                     <div class="col-md-12" style="margin-top: 2%">  
  59.                         <div class="form-group col-md-4">  
  60.                             <asp:TextBox runat="server" CssClass="form-control" ID="txtSecurityCode" MaxLength="50" ToolTip="Please enter security code you get on your authenticator application">  
  61.                             </asp:TextBox>  
  62.                         </div>  
  63.                         <asp:Button ID="btnValidate" OnClick="btnValidate_Click" CssClass="btn btn-primary" runat="server" Text="Validate" />  
  64.                     </div>  
  65.                     <h3>Result:</h3>  
  66.                     <div class="alert alert-success col-md-12" runat="server" role="alert">  
  67.                         <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>  
  68.                     </div>  
  69.                 </div>  
  70.             </div>  
  71.         </div>  
  72.     </form>  
  73. </body>  
  74. </html>  
Authenticator Code Behind Logic
  1. using Google.Authenticator;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8.   
  9. namespace _2Fa_4_5_1  
  10. {  
  11.     public partial class Authenticator : System.Web.UI.Page  
  12.     {  
  13.   
  14.   
  15.         String AuthenticationCode  
  16.         {  
  17.             get  
  18.             {  
  19.                 if (ViewState["AuthenticationCode"] != null)  
  20.                     return ViewState["AuthenticationCode"].ToString().Trim();  
  21.                 return String.Empty;  
  22.             }  
  23.             set  
  24.             {  
  25.                 ViewState["AuthenticationCode"] = value.Trim();  
  26.             }  
  27.         }  
  28.   
  29.         String AuthenticationTitle  
  30.         {  
  31.             get  
  32.             {  
  33.                 return "Ankush";  
  34.             }  
  35.         }  
  36.   
  37.   
  38.         String AuthenticationBarCodeImage  
  39.         {  
  40.             get;  
  41.             set;  
  42.         }  
  43.   
  44.         String AuthenticationManualCode  
  45.         {  
  46.             get;  
  47.             set;  
  48.         }  
  49.   
  50.         protected void Page_Load(object sender, EventArgs e)  
  51.         {  
  52.             if (!Page.IsPostBack)  
  53.             {  
  54.                 lblResult.Text = String.Empty;  
  55.                 lblResult.Visible = false;  
  56.                 GenerateTwoFactorAuthentication();  
  57.                 imgQrCode.ImageUrl = AuthenticationBarCodeImage;  
  58.                 lblManualSetupCode.Text = AuthenticationManualCode;  
  59.                 lblAccountName.Text = AuthenticationTitle;  
  60.             }  
  61.         }  
  62.   
  63.         protected void btnValidate_Click(object sender, EventArgs e)  
  64.         {  
  65.             String pin = txtSecurityCode.Text.Trim();  
  66.             Boolean status = ValidateTwoFactorPIN(pin);  
  67.             if (status)  
  68.             {  
  69.                 lblResult.Visible = true;  
  70.                 lblResult.Text = "Code Successfully Verified.";  
  71.             }  
  72.             else  
  73.             {  
  74.                 lblResult.Visible = true;  
  75.                 lblResult.Text = "Invalid Code.";  
  76.             }  
  77.         }  
  78.   
  79.         public Boolean ValidateTwoFactorPIN(String pin)  
  80.         {  
  81.             TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();  
  82.             return tfa.ValidateTwoFactorPIN(AuthenticationCode, pin);  
  83.         }  
  84.   
  85.         public Boolean GenerateTwoFactorAuthentication()  
  86.         {  
  87.             Guid guid = Guid.NewGuid();  
  88.             String uniqueUserKey = Convert.ToString(guid).Replace("-""").Substring(0, 10);  
  89.             AuthenticationCode = uniqueUserKey;  
  90.   
  91.             Dictionary<String, String> result = new Dictionary<String, String>();  
  92.             TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();  
  93.             var setupInfo = tfa.GenerateSetupCode("Complio", AuthenticationTitle, AuthenticationCode, 300, 300);  
  94.             if (setupInfo != null)  
  95.             {  
  96.                 AuthenticationBarCodeImage = setupInfo.QrCodeSetupImageUrl;  
  97.                 AuthenticationManualCode = setupInfo.ManualEntryKey;  
  98.                 return true;  
  99.             }  
  100.             return false;  
  101.         }  
  102.     }  
  103. }  
Output
 
Google Authenticator In ASP.NET
 
After scanning a barcode you will get a 6 digit code and after inserting a code and  hitting validate you will see the below result:
 
Google Authenticator In ASP.NET
 
Note
You can also download the source code in the attachment.
 

Configure two-factor authentication in ASP.NET

 
Step 1 - Install Google Authenticator
 
Please download and install GA (Google Authenticator) on your smartphone.
 
Launch the GA application
 
Google Authenticator In ASP.NET
 
Step 2 - Link your smartphone to your account
 
We have two options to link our smartphone,
  1. Barcode Scan
    Select Scan a barcode, and you will get the output as shown below.

  2. Enter Mannual Code
    Select Enter provided key, and enter your code as shown below
Google Authenticator In ASP.NET