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
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Authenticator.aspx.cs" Inherits="_2Fa_4_5_1.Authenticator" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
- </head>
- <body>
- <form id="form1" runat="server">
- <div class="container">
- <div class="jumbotron">
- <h2 class="text-info text-center">Google Authenticator</h2>
- <hr />
- <div class="row">
- <div class="col-md-12">
- <div class="section">
- <h3 class="text-info">Step 1: Install Google Authenticator
- </h3>
- <p>Please download and install Google Authenticator on your IPhone/IPad/Android device, if already not installed.</p>
- </div>
- </div>
- <div class="col-md-12">
- <div class="section">
- <h3 class="text-info">Step 2: Link your device to your account:
- </h3>
- <p>You have two options to link your device to your account:</p>
- <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>
-
- <p>
- <b>Using Secret Key:</b>
- 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.
- </p>
- </div>
- </div>
- <div class="col-md-12">
- <div class="col-md-4">
- <asp:Image ID="imgQrCode" runat="server" />
- </div>
- <div class="col-md-6">
- <div>
- <span style="font-weight: bold; font-size: 14px;">Account Name:</span>
- </div>
- <div>
- <asp:Label runat="server" ID="lblAccountName"></asp:Label>
- </div>
-
- <div>
- <span style="font-weight: bold; font-size: 14px;">Secret Key:</span>
- </div>
- <div>
- <asp:Label runat="server" ID="lblManualSetupCode"></asp:Label>
- </div>
- </div>
- </div>
- <div class="clearfix"></div>
- <div class="col-md-12" style="margin-top: 2%">
- <div class="form-group col-md-4">
- <asp:TextBox runat="server" CssClass="form-control" ID="txtSecurityCode" MaxLength="50" ToolTip="Please enter security code you get on your authenticator application">
- </asp:TextBox>
- </div>
- <asp:Button ID="btnValidate" OnClick="btnValidate_Click" CssClass="btn btn-primary" runat="server" Text="Validate" />
- </div>
- <h3>Result:</h3>
- <div class="alert alert-success col-md-12" runat="server" role="alert">
- <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
- </div>
- </div>
- </div>
- </div>
- </form>
- </body>
- </html>
Authenticator Code Behind Logic
- using Google.Authenticator;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace _2Fa_4_5_1
- {
- public partial class Authenticator : System.Web.UI.Page
- {
-
-
- String AuthenticationCode
- {
- get
- {
- if (ViewState["AuthenticationCode"] != null)
- return ViewState["AuthenticationCode"].ToString().Trim();
- return String.Empty;
- }
- set
- {
- ViewState["AuthenticationCode"] = value.Trim();
- }
- }
-
- String AuthenticationTitle
- {
- get
- {
- return "Ankush";
- }
- }
-
-
- String AuthenticationBarCodeImage
- {
- get;
- set;
- }
-
- String AuthenticationManualCode
- {
- get;
- set;
- }
-
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- lblResult.Text = String.Empty;
- lblResult.Visible = false;
- GenerateTwoFactorAuthentication();
- imgQrCode.ImageUrl = AuthenticationBarCodeImage;
- lblManualSetupCode.Text = AuthenticationManualCode;
- lblAccountName.Text = AuthenticationTitle;
- }
- }
-
- protected void btnValidate_Click(object sender, EventArgs e)
- {
- String pin = txtSecurityCode.Text.Trim();
- Boolean status = ValidateTwoFactorPIN(pin);
- if (status)
- {
- lblResult.Visible = true;
- lblResult.Text = "Code Successfully Verified.";
- }
- else
- {
- lblResult.Visible = true;
- lblResult.Text = "Invalid Code.";
- }
- }
-
- public Boolean ValidateTwoFactorPIN(String pin)
- {
- TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
- return tfa.ValidateTwoFactorPIN(AuthenticationCode, pin);
- }
-
- public Boolean GenerateTwoFactorAuthentication()
- {
- Guid guid = Guid.NewGuid();
- String uniqueUserKey = Convert.ToString(guid).Replace("-", "").Substring(0, 10);
- AuthenticationCode = uniqueUserKey;
-
- Dictionary<String, String> result = new Dictionary<String, String>();
- TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
- var setupInfo = tfa.GenerateSetupCode("Complio", AuthenticationTitle, AuthenticationCode, 300, 300);
- if (setupInfo != null)
- {
- AuthenticationBarCodeImage = setupInfo.QrCodeSetupImageUrl;
- AuthenticationManualCode = setupInfo.ManualEntryKey;
- return true;
- }
- return false;
- }
- }
- }
Output
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:
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
Step 2 - Link your smartphone to your account
We have two options to link our smartphone,
- Barcode Scan
Select Scan a barcode, and you will get the output as shown below.
- Enter Mannual Code
Select Enter provided key, and enter your code as shown below