Search code examples
asp.net-mvcauthenticationgoogle-oauth

Google Authenticator ValidateTwoFactorPIN(UserUniqueKey, token) always false MVC 5


Hello frieds i'm trying to implement 2FA with google authenticator but i'm not able to get in working.

i'm following the next article http://demo.dotnetawesome.com/two-factor-authentication-in-aspnet-mvc

I have been read that I have to synchronize time correction for codes but when i try google authenticator app says Time already correct

Any idea? Thanks

public class HomeController : Controller
{
    private const string key = "Max@123456"; // any 10-12 char string for use as private key in google authenticator
    public ActionResult Login()
    {
        return View();
    }

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

        //check username and password form our database here
        //for demo I am going to use Admin as Username and Password1 as Password static value
        if (login.Username == "Admin" && login.Password == "Password1")
        {
            status = true; // show 2FA form
            message = "2FA Verification";
            Session["Username"] = login.Username;

            //2FA Setup
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            string UserUniqueKey = login.Username + key; //as Its a demo, I have done this way. But you should use any encrypted value here which will be unique value per user 
            Session["UserUniqueKey"] = UserUniqueKey;
            var setupInfo = tfa.GenerateSetupCode("NAVIGIA 2FA", 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 ActionResult MyProfile()
    {
        if (Session["Username"] == null || Session["IsValid2FA"] == null || !(bool)Session["IsValid2FA"])
        {
            return RedirectToAction("Login");
        }
        ViewBag.Message = "Welcome " + Session["Username"].ToString();
        return View();
    }
    public ActionResult Verify2FA()
    {
        var token = Request["passcode"];
        TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
        string UserUniqueKey = Session["UserUniqueKey"].ToString();
        bool isValid = tfa.ValidateTwoFactorPIN(UserUniqueKey, token);
        if (isValid)
        {
            Session["IsValid2FA"] = true;
            return RedirectToAction("MyProfile", "Home");
        }
        return RedirectToAction("Login", "Home");
    }
}

Solution

  • I found my problem. It was with time zone. I set automatic time and zone and now is working good.

    thanks every body