Haneef Puttur

Google 2 Step Authenticator – MVC 5.0 ASP.Net C#

Requirement :

Features :

  1. Highly Secure
  2. No need of internet to get OTP Code
  3. No cost for OTP code unlike SMS
  4. No need to wait long to get a code
  5. Both IOS and Android are supported
  6. Complete solution with source code available for download
  7. 30 Days cookie so no need to authenticate daily [Can be changed]
  8. Easily add or edit private secure code in web config.
  9. Enable 2 step feature from Web.config
  10. The session cookie is Encrypted for security purpose

Source Code :

Download complete source code from my repository: https://github.com/haneefputtur/GauthenticatorMVC5

Steps :

  1. Create a blank MVC Project
  2. Install Google Authenticator from Nuget Package 3. Add New Controller and name as LoginController Copy Below Code to controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Security;
using GAuthenticator.Models;
using Google.Authenticator;

namespace GAuthenticator.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
      
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            string message = "";
            bool status = false;
            //check UserName and password form our database here
            string GAuthPrivKey = WebConfigurationManager.AppSettings["GAuthPrivateKey"];
            string UserUniqueKey = (login.UserName + GAuthPrivKey);
            if (login.UserName == "Admin" && login.Password == "12345") // Admin as user name and 12345 as Password
            {
                status = true;
                Session["UserName"] = login.UserName;

                if (WebConfigurationManager.AppSettings["GAuthEnable"].ToString() == "1")
                {
                    HttpCookie TwoFCookie = Request.Cookies["TwoFCookie"];
                    int k = 0;
                    if (TwoFCookie == null)
                    {
                        k = 1;
                    }
                    else
                    {

                        if (!string.IsNullOrEmpty(TwoFCookie.Values["UserCode"]))
                        {
                            string UserCodeE = TwoFCookie.Values["UserCode"].ToString();
                            string UserCodeD = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(UserCodeE)));


                            if (UserUniqueKey == UserCodeD)
                            {
                                FormsAuthentication.SetAuthCookie(Session["Username"].ToString(), false);
                                ViewBag.Message = "Welcome to Mr. " + Session["Username"].ToString();
                                //return View("UserProfile");
                                return RedirectToAction("UserProfile");
                            }
                            else
                            {
                                k = 1;
                            }


                        }
                    }

                    if (k == 1)
                    {

                        message = "Two Factor Authentication Verification";

                        //Two Factor Authentication Setup
                        TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();

                        Session["UserUniqueKey"] = UserUniqueKey;
                        var setupInfo = TwoFacAuth.GenerateSetupCode("HaneefPuttur.com", login.UserName, UserUniqueKey, 300, 300);
                        ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                        ViewBag.SetupCode = setupInfo.ManualEntryKey;
                    }
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(Session["Username"].ToString(), true);
                    ViewBag.Message = "Welcome to Mr. " + Session["Username"].ToString();
                    //       return View("UserProfile");
                    return RedirectToAction("UserProfile");
                }

            }

            else
            {
                message = "Please Enter the Valid Credential!";
            }
            ViewBag.Message = message;
            ViewBag.Status = status;
            return View();
        }
        [Authorize]
        public ActionResult UserProfile()
        {
            //if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
            //{
            //    return RedirectToAction("Login");
            //}
            ViewBag.Message = "Welcome to  " + 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)
            {
                HttpCookie TwoFCookie = new HttpCookie("TwoFCookie");
                string UserCode = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(UserUniqueKey)));

                TwoFCookie.Values.Add("UserCode", UserCode);
                TwoFCookie.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(TwoFCookie);
                Session["IsValidTwoFactorAuthentication"] = true;
                return RedirectToAction("UserProfile", "Login");
            }
            return RedirectToAction("Login", "Login");
        }
        public ActionResult Logoff()
        {
            Session["UserName"] = null;
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
            return RedirectToAction("Login");
        }
    }
}

Create New Model called LoginModel

 

Add Below Code to the file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

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

 

Create View Login.cshtml and copy the code from this link : https://github.com/haneefputtur/GauthenticatorMVC5/blob/master/GAuthenticator/Views/Login/Login.cshtml

Create View UserProfile.cshtml and copy the code from this link

https://github.com/haneefputtur/GauthenticatorMVC5/blob/master/GAuthenticator/Views/Login/UserProfile.cshtml

 

Edit the shared layout to reflect below changes. full code available at https://github.com/haneefputtur/GauthenticatorMVC5/blob/master/GAuthenticator/Views/Shared/_Layout.cshtml

 

Add the below keys to web.config which will control the behavior of Google Authenticator

 

Add Authorize code to Home / Index.cshtml as shown to secure the home controller for testing code

 

Download Complete code from GitHub

Install google authenticator for android from Google :

 

For IOS download from Apple Playstore

Now run the code.

You will see below screen

Now open google Authenticator app in your smart phone and scan the bar code to add

Enter the code and Click Submit query in our login page!

 

Exit mobile version