Two Factor Authentication with Google Authenticator App

Two Factor Authentication
It also Known as dual-factor authentication. Basically, Two-factor authentication is a security process where users have to provide two authentication factors for verifying their identity. It adds an additional security towards the authentication process of a system. Hence for example, according to the two-factor authentication user have to enter their username and password as a primary case then if the above is verified he has to authenticate with one of his possession factor such as a security token, mobile phone, id card etc..
Google Authenticator
As per the information from Wikipedia, Google Authenticator is a software token that implements two-step verification services using the Time-based One-time Password Algorithm and HMAC-based One-time Password Algorithm, for authenticating users of mobile applications by Google.
Google Authenticator mobile app is available in the following play store Link:
Integrating the Two Factor Authentication with Google Authenticator
I will demonstrate the integration process with ASP.NET MVC Web Application.
First of all, we have to install the nugget package for Google Authenticator.you will get it by just searching in the nugget package manager console with the same name. The Application should have a unique Key. you can add your own key. And Once the basic authentication process is completed, we have to generate the qrcode image url and manual entry key.you can use the following code:

  private const string key = "qazqaz12345"; //You can add your own Key but should be unique for the entire application
    TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
                string UserUniqueKey = (login.UserName + key);
                Session["UserUniqueKey"] = UserUniqueKey;
                var setupInfo = TwoFacAuth.GenerateSetupCode("Dot Net Detail", login.UserName, UserUniqueKey, 300, 300);
                ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                ViewBag.SetupCode = setupInfo.ManualEntryKey;

Once the QR code image URL and manual entry key are added, we have to show the QR code as well as manual entry key in the view. And also we should keep a form for inputting the OTP generated from the Google authenticator app after QR code or manual entry key verification. The view will be similar like this:

    <div>
        <img src="@ViewBag.BarcodeImageUrl" />
    </div>
    <div>
        Manual Setup Code : @ViewBag.SetupCode
    </div>
    <div>
        @using (Html.BeginForm("TwoFactorAuthenticate", "Home", FormMethod.Post))
        {
            <input type="text" name="CodeDigit" />
            <input type="submit" class="btn btn-success" />
        }
    </div>
After setting up the view we have to set up an action result for handling the form post from the above page. And from this action result we can verify the validity of key entered. Also using the result we can handle all other system specific requirements of the Application. The code will look like this:

public ActionResult TwoFactorAuthenticate()
        {
            var token = Request["CodeDigit"];
            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string UserUniqueKey = Session["UserUniqueKey"].ToString();
            bool isValid = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token);
            if (isValid)
            {
                Session["IsValidTwoFactorAuthentication"] = true;
                return RedirectToAction("UserProfile", "Home");
            }
            return RedirectToAction("Login", "Home");
        }

Hence the Whole Application Code will look like this:
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GoogleAuth.Models
{
    public class LoginModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}


Controller

using Google.Authenticator;
using GoogleAuth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GoogleAuth.Controllers
{
    public class HomeController : Controller
    {
       
        private const string key = "qazqaz12345"; //You can add your own Key
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            string message = "";
            bool status = false;
            //check UserName and password form our database here
            if (login.UserName == "Admin" && login.Password == "12345") // Admin as user name and 12345 as Password
            {
                status = true;
                message = "Two Factor Authentication Verification";
                Session["UserName"] = login.UserName;
                //Two Factor Authentication Setup
                TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
                string UserUniqueKey = (login.UserName + key);
                Session["UserUniqueKey"] = UserUniqueKey;
                var setupInfo = TwoFacAuth.GenerateSetupCode("Dot Net Detail", login.UserName, UserUniqueKey, 300, 300);
                ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                ViewBag.SetupCode = setupInfo.ManualEntryKey;
            }
            else
            {
                message = "Please Enter the Valid Credential!";
            }
            ViewBag.Message = message;
            ViewBag.Status = status;
            return View();
        }

        public ActionResult UserProfile()
        {
            if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
            {
                return RedirectToAction("Login");
            }
            ViewBag.Message = "Welcome to Mr. " + Session["Username"].ToString();
            return View();
        }

        public ActionResult TwoFactorAuthenticate()
        {
            var token = Request["CodeDigit"];
            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string UserUniqueKey = Session["UserUniqueKey"].ToString();
            bool isValid = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token);
            if (isValid)
            {
                Session["IsValidTwoFactorAuthentication"] = true;
                return RedirectToAction("UserProfile", "Home");
            }
            return RedirectToAction("Login", "Home");
        }   
    }
}

View
Login.cshtml
@model GoogleAuth.Models.LoginModel
@{
    ViewBag.Title = "Login";
}
<h2>Login Page</h2>
@if (ViewBag.Status == null || !ViewBag.Status)
{
    <div>@ViewBag.Message</div>
    <div>
        @using (Html.BeginForm())
        {
            <div class="form-group">
                <label for="UserName">UserName : </label>
                @Html.TextBoxFor(a => a.UserName, new { @class = "form-control" })
            </div>
            <div class="form-group">
                <label for="Password">Password : </label>       
                @Html.PasswordFor(a => a.Password, new { @class = "form-control", type = "password" })
            </div>
            <input type="submit" value="Login" class="btn btn-default" />
        }
    </div>
}
else
{
    <div>@ViewBag.Message</div>
    <div>
        <img src="@ViewBag.BarcodeImageUrl" />
    </div>
    <div>
        Manual Setup Code : @ViewBag.SetupCode
    </div>
    <div>
        @using (Html.BeginForm("TwoFactorAuthenticate", "Home", FormMethod.Post))
        {
            <input type="text" name="CodeDigit" />
            <input type="submit" class="btn btn-success" />
        }
    </div>
}







Comments

  1. bool isValid = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token); always false
    i don't know why

    ReplyDelete
  2. Thanks for sharing Multi Factor Authentication tips. for more info i rfer cion systems active Multi Factor Authentication in USA.

    ReplyDelete

Post a Comment