Exemplo n.º 1
0
        public ActionResult Google2Auth(string token)
        {
            using (var dbContext = new MazzaDbContext())
            {
                var userId = User.Identity.GetUserId <int>();
                var userGA = dbContext.GoogleAuths.FirstOrDefault(g => g.UserId == userId);

                string message = string.Empty;
                string status  = string.Empty;
                if (!userGA.IsActive)
                {
                    var validate = tfa.ValidateTwoFactorPIN(userGA.AccountSecretKey, token, TimeSpan.FromSeconds(5));
                    if (validate)
                    {
                        userGA.IsActive = true;
                        dbContext.SaveChanges();
                        status  = Success;
                        message = "Change with success";
                    }
                    else
                    {
                        status  = Danger;
                        message = "Error";
                    }
                }
                return(Json(new { success = true, Status = status, Message = message }));
            }
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        /// <summary>
        /// Explicitly implement this interface method - which overrides the base class's implementation
        /// </summary>
        /// <param name="purpose"></param>
        /// <param name="token"></param>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        Task <bool> IUserTokenProvider <BackOfficeIdentityUser, int> .ValidateAsync(string purpose, string token, UserManager <BackOfficeIdentityUser, int> manager, BackOfficeIdentityUser user)
        {
            if (purpose == Constants.GoogleAuthenticatorProviderName)
            {
                var twoFactorAuthenticator = new TwoFactorAuthenticator();
                var database = ApplicationContext.Current.DatabaseContext.Database;
                var result   = database.Fetch <TwoFactor>(string.Format("WHERE [userId] = {0} AND [key] = '{1}' AND [confirmed] = 1",
                                                                        user.Id, Constants.GoogleAuthenticatorProviderName));
                if (result.Any() == false)
                {
                    return(Task.FromResult(false));
                }

                var key        = result.First().Value;
                var validToken = twoFactorAuthenticator.ValidateTwoFactorPIN(key, token);
                return(Task.FromResult(validToken));
            }

            /* if (purpose == Constants.YubiKeyProviderName)
             * {
             *   var yubiKeyService = new YubiKeyService();
             *   var response = yubiKeyService.Validate(token, user.Id);
             *   return Task.FromResult(response != null && response.Status == YubicoResponseStatus.Ok);
             * }*/

            return(Task.FromResult(false));
        }
Exemplo n.º 3
0
        public bool CheckTFA(string tfa)
        {
            BsonDocument           acc  = Projected(TFA_INTERNAL);
            TwoFactorAuthenticator tfao = new TwoFactorAuthenticator();

            return(tfao.ValidateTwoFactorPIN(acc[TFA_INTERNAL].AsString, tfa));
        }
Exemplo n.º 4
0
        public TwoFactorValidation ValidateGoogleAuthSetup(string twoFactorCode)
        {
            var model   = new TwoFactorValidation();
            var userId  = Security.GetUserId();
            var details = CustomDatabase.GetUserDetails(userId);

            if (details != null && details.IsValidated)
            {
                throw new UnauthorizedAccessException("This account has already setup GoogleAuthenticator");
            }

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            var isValid = tfa.ValidateTwoFactorPIN(details.Configuration, twoFactorCode);

            if (isValid)
            {
                details.IsValidated = true;
                CustomDatabase.Update(details);
                model.IsValid  = true;
                model.Settings = GetMySettings();
            }
            else
            {
                model.IsValid = false;
            }
            return(model);
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        /// <summary>
        /// Explicitly implement this interface method - which overrides the base class's implementation
        /// </summary>
        /// <param name="purpose"></param>
        /// <param name="token"></param>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        async Task <bool> IUserTokenProvider <BackOfficeIdentityUser, int> .ValidateAsync(string purpose, string token, UserManager <BackOfficeIdentityUser, int> manager, BackOfficeIdentityUser user)
        {
            if (purpose == Constants.GoogleAuthenticatorProviderName)
            {
                var twoFactorAuthenticator = new TwoFactorAuthenticator();

                using (var scope = Current.ScopeProvider.CreateScope(autoComplete: true))
                {
                    var result = await scope.Database.Query <TwoFactor>()
                                 .Where(x => x.UserId == user.Id && x.Key == Constants.GoogleAuthenticatorProviderName && x.Confirmed)
                                 .ToListAsync();

                    if (result.Any() == false)
                    {
                        return(false);
                    }

                    var key        = result.First().Value;
                    var validToken = twoFactorAuthenticator.ValidateTwoFactorPIN(key, token);
                    return(validToken);
                }
            }

            /* if (purpose == Constants.YubiKeyProviderName)
             * {
             *   var yubiKeyService = new YubiKeyService();
             *   var response = yubiKeyService.Validate(token, user.Id);
             *   return Task.FromResult(response != null && response.Status == YubicoResponseStatus.Ok);
             * }*/

            return(false);
        }
        public static bool ValidateCode(string userAccountSecreteKey, string code)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            bool isCorrectPin          = tfa.ValidateTwoFactorPIN(userAccountSecreteKey, code, new TimeSpan(0, 15, 0));

            return(isCorrectPin);
        }
Exemplo n.º 7
0
        public static bool ValidateTwoFactorPasscode(User user, CMSDataContext db, string passcode)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var secretKey = Get2FASecret(db);

            return(passcode?.Length == 6 && tfa.ValidateTwoFactorPIN(Get2FAUserSecret(user, secretKey), passcode));
        }
Exemplo n.º 8
0
        public ActionResult TwoFactorAuthenticate(string CodeDigit)
        {
            var token = CodeDigit;
            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string UserUniqueKey = Session["UserUniqueKey"].ToString();
            bool   isValid       = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token);

            if (isValid)
            {
                string email      = Session["UserEmail"].ToString();
                string password   = Session["UserPassword"].ToString();
                bool   rememberMe = (bool)Session["RememberMe"];

                CleanSessionValues();

                var result = _signInManager.PasswordSignIn(EncryptionService.EncryptEmail(email), password, rememberMe, true);

                if (result == SignInStatus.Success)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                return(RedirectToAction("Login", "Home"));
            }

            CleanSessionValues();

            return(RedirectToAction("Login", "Home"));
        }
Exemplo n.º 9
0
        public ActionResult TwoFactorAuthenticateSetup(string CodeDigit)
        {
            string userId = User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
                RedirectToAction("Index", "Home");
            }

            var token = CodeDigit;
            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string UserUniqueKey = Session["UserUniqueKey"].ToString();
            bool   isValid       = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token);

            var user = _userManager.FindById(userId);

            if (isValid)
            {
                Session["UserUniqueKey"] = null;

                user.TwoFactorEnabled = true;
                _userManager.Update(user);

                return(RedirectToAction("Index", "Home"));
            }

            return(RedirectToAction("UserSettings", "Home"));
        }
Exemplo n.º 10
0
        public bool TestTwoFactorCode(string secretKey, string code)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var result = tfA.ValidateTwoFactorPIN(secretKey, code);

            return(result);
        }
Exemplo n.º 11
0
        public async Task <ActionResult> Verify2Fa(string returnUrl = "/")
        {
            int count = Session["Count"] != null ? Session["Count"].MapInt():0;
            //var count = 0;
            var message       = "Sử dụng ứng dụng Google Authenticator để quét mã QR:";
            var token         = Request["passcode"];
            var authenticator = new TwoFactorAuthenticator();
            var isValid       = authenticator.ValidateTwoFactorPIN(Key, token);

            if (isValid)
            {
                var result = await  OnLogin();

                Session["IsValid2FA"] = true;

                return(Redirect(returnUrl));
            }
            else
            {
                var countLimit = Ultilities.Common.GetByKey("countInputError").MapInt();
                count++;
                if (count >= countLimit)
                {
                    return(LogOff());
                }
                var authenticator1 = new TwoFactorAuthenticator();
                var result         = authenticator1.GenerateSetupCode("Sao Ha Thanh", "SHT Login", Key, 300, 300);
                ViewBag.BarcodeImageUrl = result.QrCodeSetupImageUrl;
                ViewBag.Message         = message;
                ViewBag.messError       = string.Format("Mã code nhập sai, xin vui lòng nhập lại!");
                Session["Count"]        = count;
                return(View("OuthenGoogle"));
            }
        }
Exemplo n.º 12
0
        public ActionResult SnimiAutentifikator(KupacAutentifikatorVM model)
        {
            Korisnik k = HttpContext.GetLogiraniKorisnik();

            if (k == null)
            {
                return(Redirect("/Autentifikacija/Index"));
            }

            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            bool isValid = TwoFacAuth.ValidateTwoFactorPIN(model.TwoFactorUserUniqueKey, model.TwoFactorPin);

            if (isValid)
            {
                k.TwoFactorUniqueKey = model.TwoFactorUserUniqueKey;
                ctx.SaveChanges();

                bool token = false;
                if (ctx.AutorizacijskiToken.Where(a => a.KorisnikId == k.Id).Count() > 0)
                {
                    token = true;
                }
                HttpContext.SetLogiraniKorisnik(k, token);
            }


            return(RedirectToAction("Index"));
        }
Exemplo n.º 13
0
        public async Task <ActionResult> IskljuciAutentifikaciju(AutentifikacijaVM model)
        {
            if (User.Identity.Name != null)
            {
                var korisnik = await UserM.FindByEmailAsync(User.Identity.Name);

                string userUniqueKey       = GetUserUniqueKey(korisnik);
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                if (LockoutCheck(korisnik))
                {
                    TimeSpan t = (korisnik.LockoutEnd - DateTime.Now) ?? default(TimeSpan);
                    ModelState.AddModelError("Lockout", "Vaš profil je zaključan još " + t.Minutes + " minuta i " + t.Seconds + " sekundi.");
                    return(View());
                }
                else
                {
                    if (tfa.ValidateTwoFactorPIN(userUniqueKey, model.Code))
                    {
                        Igrac i = db.Igraci.Find(korisnik.Id);
                        i.TwoFactorEnabled = false;
                        db.Update(i);
                        db.SaveChanges();
                        return(Redirect("/Igrac/PrikazProfila/" + i.ID));
                    }
                    else
                    {
                        ModelState.AddModelError("Code", "Neispravan kod");
                        return(View());
                    }
                }
            }
            return(RedirectToAction("Login"));
        }
Exemplo n.º 14
0
        public bool ValidateTwoFactorPIN(long accountId, string pin)
        {
            var authenticationCode = accountId.ToString() + "ULTRABACK";
            TwoFactorAuthenticator authenticator = new TwoFactorAuthenticator();

            return(authenticator.ValidateTwoFactorPIN(authenticationCode, pin));
        }
Exemplo n.º 15
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var result = tfA.ValidateTwoFactorPIN(txtSecretKey.Text, this.txtCode.Text);

            MessageBox.Show(result ? "Validated!" : "Incorrect", "Result");
        }
Exemplo n.º 16
0
        protected void activateBtn_Click(object sender, EventArgs e)
        {
            string key                 = ViewState["key"].ToString();
            string user_enter          = gAuthPassTb.Text;
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            bool isCorrectPIN          = tfa.ValidateTwoFactorPIN(key, user_enter);

            if (isCorrectPIN == true)
            {
                UserBO userbo = new UserBO();
                userbo.activate2FA(Request.Cookies["CurrentLoggedInUser"].Value, key);


                GoogleAuthErrorMsgLabel.Text = "";
                gAuthCard.Visible            = false;
                mainPanel.Visible            = true;
                gAuthEnableLink.Visible      = false;
                gAuthDisableLink.Visible     = true;
                gAuthSuccessMessage.Text     = "Google Authenticator Activated";
            }
            else
            {
                GoogleAuthErrorMsgLabel.Text = "Incorrect PIN entered";
            }
        }
Exemplo n.º 17
0
        protected void btnVerifyCode_Click(object sender, EventArgs e)
        {
            Page.Validate(valGroup);
            if (!Page.IsValid)
            {
                return;
            }

            if (String.IsNullOrEmpty(AuthCode))
            {
                throw new InvalidOperationException("Validation required but no authcode provided");
            }

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            if (tfa.ValidateTwoFactorPIN(AuthCode, txtCode.Text, new TimeSpan(0, 2, 0)))
            {
                TFACodeVerified?.Invoke(this, new EventArgs());
            }
            else
            {
                FailureCount++;
                System.Threading.Thread.Sleep(1000); // pause for a second to thwart dictionary attacks.
                TFACodeFailed?.Invoke(this, new EventArgs());
            }
            txtCode.Text = string.Empty;    // clear it regardless.
        }
Exemplo n.º 18
0
 public HttpStatusCode AuthenticateUser([FromBody] AuthRequest request)
 {
     try
     {
         //Get user secret from table
         bool validated = false;
         _dbConnection.Open();
         using (var command = new SQLiteCommand($"SELECT Secret FROM Users WHERE Id='{request.UserId}'", _dbConnection))
         {
             var reader = command.ExecuteReader();
             reader.Read();
             var secret = reader.GetString(0);
             TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
             validated = tfa.ValidateTwoFactorPIN(secret, request.Code, TimeSpan.FromMinutes(2));
         }
         if (!validated)
         {
             throw new Exception();
         }
         UsersController.SessionUsers[request.UserId] = DateTime.Now;
         Response.StatusCode = 200;
         return(HttpStatusCode.OK);
     }
     catch
     {
         Response.StatusCode = 400;
         return(HttpStatusCode.BadRequest);
     }
 }
Exemplo n.º 19
0
        private bool ValidateGoogleCode()
        {
            string UserName = null;

            if (System.Web.HttpContext.Current.Request.Cookies["PPusernameMerchant"] != null)
            {
                UserName = ClassLibrary1.ClassAccount.cookie解密(System.Web.HttpContext.Current.Request.Cookies["PPusernameMerchant"]["username"]);
            }
            if (UserName != null)
            {
                using (var db = (new DBClient()).GetClient())
                {
                    var data = db.Queryable <Sugar.Enties.table_商户账号>().Where(it => it.商户ID == UserName).First();
                    if (data.二步验证状态 == true)
                    {
                        if (TextGoogleValidate.Text.Length != 6)
                        {
                            ClassLibrary1.ClassMessage.HinXi(Page, "验证码不和规范");
                            return(false);
                        }
                        TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

                        var result = tfa.ValidateTwoFactorPIN(data.keyga, TextGoogleValidate.Text);
                        if (!result)
                        {
                            ClassLibrary1.ClassMessage.HinXi(Page, "验证码错误");
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
Exemplo n.º 20
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var result = tfA.ValidateTwoFactorPIN(txtSecretKey.Text, this.txtCode.Text);

            MessageBox.Show(result ? "Validated!" : "Incorrect", "Result");
        }
Exemplo n.º 21
0
        private void 更新内容()//更新出去
        {
            if (TextBox_后台账号名称.Text.Length > 1)
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                var result = tfa.ValidateTwoFactorPIN(获取密匙(), TextBox_验证密匙.Text);

                if (result)
                {
                    //this.lblValidationResult.Text = this.txtCode.Text + " 是UTC时间内有效PIN码 " + DateTime.UtcNow.ToString();
                    //this.lblValidationResult.ForeColor = System.Drawing.Color.Green;


                    操作更新();
                }
                else
                {
                    ClassLibrary1.ClassMessage.HinXi(Page, "KEY错误");

                    //this.lblValidationResult.Text = this.txtCode.Text + " 是UTC时间内不有效的PIN码 " + DateTime.UtcNow.ToString();
                    //this.lblValidationResult.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                ClassLibrary1.ClassMessage.HinXi(Page, "检查所有栏位是否都已填写");
            }
        }
Exemplo n.º 22
0
        public Task <bool> ValidateAsync(string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user)
        {
            //validate userinput with current token with corresponding user secret
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            return(Task.FromResult(tfa.ValidateTwoFactorPIN(user.GoogleAuthSecret, tfa.GetCurrentPIN(user.GoogleAuthSecret))));
        }
Exemplo n.º 23
0
        public virtual async Task <bool> AuthenticateTwoFactor(string secretKey, string token, Customer customer, TwoFactorAuthenticationType twoFactorAuthenticationType)
        {
            switch (twoFactorAuthenticationType)
            {
            case TwoFactorAuthenticationType.AppVerification:
                return(_twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim()));

            case TwoFactorAuthenticationType.EmailVerification:
                var customertoken = customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.TwoFactorValidCode);
                if (customertoken != token.Trim())
                {
                    return(false);
                }
                var validuntil = customer.GetAttributeFromEntity <DateTime>(SystemCustomerAttributeNames.TwoFactorCodeValidUntil);
                if (validuntil < DateTime.UtcNow)
                {
                    return(false);
                }

                return(true);

            case TwoFactorAuthenticationType.SMSVerification:
                var smsVerificationService = _serviceProvider.GetRequiredService <ISMSVerificationService>();
                return(await smsVerificationService.Authenticate(secretKey, token.Trim(), customer));

            default:
                return(false);
            }
        }
Exemplo n.º 24
0
        protected void btnValidateTwoFactor_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            string pin = txttwofactorcode.Text;

            if (pin == "")
            {
                MsgBox("Pin Empty", "Sorry, the pin is empty.  Unable to test the code.  Please click back and try again. ", this);
            }
            bool   fPassed = tfa.ValidateTwoFactorPIN(gUser(this).UserId, pin);
            string sNarr   = fPassed ? "Success.  <br>Your Two-factor authentication code has been set successfully and verified.  <br><br>Next time you log in you will be required to paste the PIN number in the 2FA box.  <br><br>Thank you.  " : "Failure!  The 2FA code does not work.  Please click back and generate a new code and try again.  ";
            string sSucNar = fPassed ? "Success" : "Fail";

            if (fPassed && gUser(this).UserName.Length > 1 && gUser(this).UserName != "Guest" && gUser(this).UserId.Length > 10)
            {
                string     sql     = "Update Users set twofactor=1 where id=@id";
                SqlCommand command = new SqlCommand(sql);
                command.Parameters.AddWithValue("@id", gUser(this).UserId);
                gData.ExecCmd(command);
                User g1 = (User)Session["CurrentUser"];
                g1.Require2FA          = 1;
                g1.TwoFactorAuthorized = true;
                Session["CurrentUser"] = g1;
                MsgBox(sSucNar, sNarr, this);
            }
        }
Exemplo n.º 25
0
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            bool   checkPin            = false;
            string pin                 = txtPIN.Text;
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            checkPin = tfa.ValidateTwoFactorPIN(("!8R8Vrreugfifbtljuf" + txtUsername.Text), pin);

            if (!checkPin)
            {
                btnSubmit.Enabled   = false;
                txtPIN.Enabled      = false;
                btnSubmit.Visible   = false;
                txtPIN.Visible      = false;
                btnLogin.Visible    = true;
                txtPassword.Visible = true;
                txtUsername.Visible = true;
                txtUsername.Text    = "";
                txtPassword.Text    = "";
                lblSuccess.Text     = "Invalid PIN";
                txtPIN.Text         = "";
            }
            else
            {
                login();
            }
        }
Exemplo n.º 26
0
        private void OK_Click(object sender, EventArgs e)
        {
            var tfa      = new TwoFactorAuthenticator();
            var verified = tfa.ValidateTwoFactorPIN(account, PasswordTextBox.Text);

            DialogResult = verified ? DialogResult.OK : DialogResult.Abort;
        }
Exemplo n.º 27
0
        protected void ProceedBtn_Click(object sender, EventArgs e)
        {
            string user_enter          = gAuthTb.Text;
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            bool isCorrectPIN          = tfa.ValidateTwoFactorPIN(ViewState["key"].ToString(), user_enter);

            if (isCorrectPIN == true)
            {
                String input_username = username_tb.Text;
                UserBO userbo         = new UserBO();
                user   returnedObj    = new user();
                returnedObj = userbo.getUserById(input_username);
                //to create session for user
                Session["LoginUserName"] = returnedObj.User_ID.ToString();
                string guid = Guid.NewGuid().ToString();
                //create second session for user and assigning a random GUID
                Session["AuthToken"] = guid;

                //Session["authWin"] = guidWN;
                //Create cokie and store the same value of second session in cookie
                Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                Response.Cookies.Add(new HttpCookie("CurrentLoggedInUser", returnedObj.User_ID.ToString()));
                Response.Cookies["AuthToken"].Expires           = DateTime.Now.AddDays(1); //so the cookie will be expired if user didn't log out properly
                Response.Cookies["CurrentLoggedInUser"].Expires = DateTime.Now.AddDays(1); //so the cookie will be expired if user didn't log out properly
                Response.Redirect("Dashboard.aspx");                                       //login pass
            }
            else
            {
                modalOverlay.Visible = false;
            }
        }
        public ActionResult Authentication(int tokken)
        {
            var user = NewspaperSBTSession.CurrentUser;

            if (user == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            TwoFactorAuthenticator tf = new TwoFactorAuthenticator();
            bool isValid = tf.ValidateTwoFactorPIN(user.tokken.ToString(), tokken.ToString());

            if (isValid)
            {
                string PageName = bal.getuserProfileStatus(user.Userid);
                if (!string.IsNullOrEmpty(PageName))
                {
                    return(RedirectToAction("Index", PageName));
                }
            }
            else
            {
                return(RedirectToAction("Authentication", "login"));
            }
            return(null);
        }
Exemplo n.º 29
0
        public ActionResult Login()
        {
            var username = Request["username"];
            var password = Request["password"];
            var token    = Request["token"];

            if (username == "yanick" && password == "yanick")
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                bool isCorrectPIN          = tfa.ValidateTwoFactorPIN("MY_SECRET_KEY", token);
                if (isCorrectPIN)
                {
                    ViewBag.Message = "Login and Token Correct";
                }
                else
                {
                    ViewBag.Message = "Wrong credentials and token";
                }
            }
            else
            {
                ViewBag.Message = "Wrong credentials";
            }

            return(View());
        }
Exemplo n.º 30
0
        public Task <bool> ValidateAsync(string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user)
        {
            TwoFactorAuthenticator autenticador = new TwoFactorAuthenticator();
            var resultado = autenticador.ValidateTwoFactorPIN(user.Id, token);

            return(Task.FromResult(resultado));
        }
        public bool ValidatePin(string pin, string secretCode)
        {
            var tfa          = new TwoFactorAuthenticator();
            var isCorrectPin = tfa.ValidateTwoFactorPIN(secretCode, pin);

            return(isCorrectPin);
        }
        protected void btnValidate_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var result = tfa.ValidateTwoFactorPIN(Request.QueryString["key"], this.txtCode.Text);

            if (result)
            {
                this.lblValidationResult.Text = this.txtCode.Text + " is a valid PIN at UTC time " + DateTime.UtcNow.ToString();
                this.lblValidationResult.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                this.lblValidationResult.Text = this.txtCode.Text + " is not a valid PIN at UTC time " + DateTime.UtcNow.ToString();
                this.lblValidationResult.ForeColor = System.Drawing.Color.Red;
            }
        }