How to integrate Google Authenticator in ASP .NET MVC Project ?

Initialize

  1. Install nuget GoogleAuthenticator.


Models

  • UserLoginModel.cs
public class UserLoginModel
{
   //Field to store the Username
   public string Username { get; set; }

   //Field to store the Password
   public string Password { get; set; }
}


Controllers

  • LoginController.cs
public class LoginController : Controller
{
  private const string key = "dfg7568!@@)(";

  public ActionResult Login()
  {
    return View();
  }

  [HttpPost]
  publiv ActionResult Login(UserLoginModel login)
  {
    string message = "";
    bool status = false;

    if("Corrent credential")
    {
      //It indicates 2FA form
      status = true; 
      message = "2FA Verification";
      Session["Username"] = login.Username;

      //2FA Setup
      TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
      string uniqueKeyforUser = (login.Username + key);
      Session["UserUniqueKey"] = UserUniqueKey;
      var setupInfo = tfa.GenerateSetupCode("Name display in Google Authenticator Application", login.Username, UserUniqueKey, 300, 300);

      ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
      ViewBag.SetupCode = setupInfo.ManualEntryKey;
    }
    else
    {
      message = "Invalid credential";
    }

    ViewBag.Message = message;
    ViewBag.Status = status;

    return View();
  }

  public bool Verify2FA()
  {
    var token = Request["passcode"];

    TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

    string UserUniqueKey = Session["UserUniqueKey"].toString();

    bool isValid = tfa.ValidateTwoFactorPIN(UserUniqueKey, token);

    if (isValid)
    {
      Session["IsValidAuthentication"] = true;
      return RedirectToAction("MyProfile", "Profile");
    }

    return RedirectToAction("Login", "Home");
  }
}
  • ProfileController.cs
public class ProfileController : Controller
{
  public ActionResult MyProfile
  {
    if (Session["Username"] == null || Session["IsValidAuthentication"] == null || !(bool)Session["IsValidAuthentication"])
    {
      return RedirectToAction("Login", "Home");
    }
    
    ViewBag.Message = "Welcome " + Session["Username"].ToString();
    
    return View();
  }
}


View

  • Login.cshtml
@model GoogleAuthenticator.ViewModel.UserLoginModel
@{
  ViewBag.Title = "UserLogin";
}

<h2>Login</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.TextBoxFor(a => a.Password, new { @class="form-control", type="password"})
      </div>
      <input type="submit" value="Login" class="btn btn-default" />
    }
  </div>
}
else
{
  <!--Show 2FA verification form here-->
  <div>@ViewBag.Message</div>
  <div> 
    <img src="@ViewBag.BarcodeImageUrl"/> 
  </div>
  <div> Manual Setup Code : @ViewBag.SetupCode </div>
  <div>
    @using (Html.BeginForm("Verify2FA","Home", FormMethod.Post))
    {
      <input type="text" name="passcode" />
      <input type="submit" class="btn btn-success" />
    }
  </div>
}
  • MyProfile.cshtml
@{
  ViewBag.Title = "AuthorizedProfile";
}
<h2>Authorized Profile</h2>

<h5>@ViewBag.Message</h5>