Example #1
0
        internal void GetCode()
        {
            var auth = new TwoStepsAuthenticator.TimeAuthenticator();

            Code = auth.GetCode(this.Key);

            auth.CheckCode(key, Code, "user");
        }
        public ActionResult DoubleAuth(string code)
        {
            WebsiteUser user = (WebsiteUser)Session["AuthenticatedUser"];
            var auth = new TwoStepsAuthenticator.TimeAuthenticator(usedCodeManager: usedCodesManager);
            if (auth.CheckCode(user.DoubleAuthKey, code, user))
            {
                FormsAuthentication.SetAuthCookie(user.Login, true);
                return RedirectToAction("Welcome");
            }

            return RedirectToAction("Index");
        }
Example #3
0
        public ActionResult DoubleAuth(string code)
        {
            WebsiteUser user = (WebsiteUser)Session["AuthenticatedUser"];
            var         auth = new TwoStepsAuthenticator.TimeAuthenticator(usedCodeManager: usedCodesManager);

            if (auth.CheckCode(user.DoubleAuthKey, code, user))
            {
                FormsAuthentication.SetAuthCookie(user.Login, true);
                return(RedirectToAction("Welcome"));
            }

            return(RedirectToAction("Index"));
        }
Example #4
0
            private static string secretKey;//模拟服务端保存的密钥//应加密后存储在服务器中

            //验证密钥
            public static bool verifySecret(string userCode)
            {
                if (secretKey == null)
                {
                    throw new NullReferenceException("当前密钥为空!");
                }
                else
                {
                    var secret        = secretKey;
                    var code          = userCode;
                    var authenticator = new TwoStepsAuthenticator.TimeAuthenticator();
                    return(authenticator.CheckCode(secret, code, "user特朗普"));
                }
            }
Example #5
0
        public ReponseApi ValidateCodeMicrosoft(DataValidateMicrosoft par)
        {
            ReponseApi res = new ReponseApi();

            res.Codigo    = 0;
            res.Mensaje   = "";
            res.Respuesta = null;

            try
            {
                if (string.IsNullOrEmpty(par.Cuenta))
                {
                    res.Mensaje = "La Cuenta no puede ser nula";
                }
                else if (string.IsNullOrEmpty(par.Secreto))
                {
                    res.Mensaje = "El Emisor no puede ser nulo";
                }
                else if (string.IsNullOrEmpty(par.Codigo))
                {
                    res.Mensaje = "El Codigo no puede ser nulo";
                }
                else
                {
                    var authenticator = new TwoStepsAuthenticator.TimeAuthenticator();

                    bool isok = authenticator.CheckCode(par.Secreto, par.Codigo, par.Cuenta);

                    if (isok != true)
                    {
                        res.Mensaje = "El Código ingresado no es correcto";
                    }
                    else
                    {
                        res.Codigo  = 1;
                        res.Mensaje = "Código Válido";
                    }
                }
            }
            catch (Exception ex)
            {
                //Log Error
                _logger.Log(LogLevel.Error, ex, ex.Message);
            }

            return(res);
        }
        public async Task <IActionResult> AdditionalAuthenticationFactor(
            AdditionalAuthenticationFactorViewModel model)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                // read identity from the temporary cookie
                var result = await HttpContext.AuthenticateAsync("idsrv.mfa");

                if (result?.Succeeded != true)
                {
                    throw new Exception("MFA authentication error");
                }

                var subject = result.Principal.FindFirst(JwtClaimTypes.Subject)?.Value;

                var user = await _localUserService.GetUserBySubjectAsync(subject);

                var userSecret = await _localUserService.GetUserSecret(subject, "TOTP");

                var authenticator = new TwoStepsAuthenticator.TimeAuthenticator();
                if (!authenticator.CheckCode(userSecret.Secret, model.Totp, user))
                {
                    ModelState.AddModelError("totp", "TOTP is invalid.");
                    return(View(model));
                }

                await _events.RaiseAsync(
                    new UserLoginSuccessEvent(
                        user.Username,
                        user.Subject,
                        user.Username,
                        clientId : context?.Client.ClientId));

                // only set explicit expiration here if user chooses "remember me".
                // otherwise we rely upon expiration configured in cookie middleware.
                AuthenticationProperties props = null;
                if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                {
                    props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   =
                            DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                    };
                }
                ;

                // delete temporary cookie used during mfa
                await HttpContext.SignOutAsync("idsrv.mfa");

                // issue authentication cookie with subject ID and username
                var isuser = new IdentityServerUser(user.Subject)
                {
                    DisplayName = user.Username
                };

                await HttpContext.SignInAsync(isuser, props);

                if (context != null)
                {
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }

                // request for a local page
                if (Url.IsLocalUrl(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                else if (string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect("~/"));
                }
                else
                {
                    // user might have clicked on a malicious link - should be logged
                    throw new Exception("invalid return URL");
                }
            }

            return(View(model));
        }
        internal void GetCode()
        {
            var auth = new TwoStepsAuthenticator.TimeAuthenticator();
            Code = auth.GetCode(this.Key);

            auth.CheckCode(key, Code);
        }
Example #8
0
        public static bool CheckCodeSms(string secret, string token, User model, int time = 30)
        {
            var authenticator = new TwoStepsAuthenticator.TimeAuthenticator(null, null, time);

            return(authenticator.CheckCode(secret, token, model));
        }
Example #9
0
        public string VerifyCodeEnable([FromBody] JObject value = null)
        {
            try
            {
                var userModel = (User)RouteData.Values[ParseDataKeyApi.KEY_PASS_DATA_USER_MODEL];

                if (userModel.IsTwoFactor == 2)
                {
                    if (!value.ContainsKey(ParseDataKeyApi.KEY_TWO_FA_VERIFY_CODE_ENABLE_CODE))
                    {
                        return(HelpersApi.CreateDataError(MessageApiError.PARAM_INVALID));
                    }

                    var code          = value[ParseDataKeyApi.KEY_TWO_FA_VERIFY_CODE_ENABLE_CODE].ToString();
                    var authenticator = new TwoStepsAuthenticator.TimeAuthenticator();

                    var secretAuthToken = ActionCode.FromJson(userModel.SecretAuthToken);

                    if (string.IsNullOrEmpty(secretAuthToken.CustomTwofa))
                    {
                        return(HelpersApi.CreateDataError(MessageApiError.SMS_VERIFY_ERROR));
                    }

                    var isOk = authenticator.CheckCode(secretAuthToken.CustomTwofa, code, userModel);

                    if (!isOk)
                    {
                        return(HelpersApi.CreateDataError(MessageApiError.SMS_VERIFY_ERROR));
                    }
                }
                else if (userModel.IsTwoFactor == 0)
                {
                    if (value.ContainsKey(ParseDataKeyApi.KEY_TWO_FA_VERIFY_CODE_ENABLE_CODE))
                    {
                        return(HelpersApi.CreateDataError(MessageApiError.PARAM_INVALID));
                    }
                }


                var google = new GoogleAuthen.TwoFactorAuthenticator();

                var secretKey = CommonHelper.RandomString(32);

                var startSetup = google.GenerateSetupCode(userModel.Email, secretKey, 300, 300);

                userModel.TwoFactorSecret = secretKey;
                Console.WriteLine(secretKey);
                var resultUpdate = _userBusiness.UpdateProfile(userModel);

                if (resultUpdate.Status == Status.STATUS_ERROR)
                {
                    return(resultUpdate.ToJson());
                }

                return(new ReturnObject
                {
                    Status = Status.STATUS_SUCCESS,
                    Data = startSetup.ManualEntryKey
                }.ToJson());
            }
            catch (Exception e)
            {
                _logger.Error(KeyLogger.TWOFA_ENABLE_VERIFY + e);
                return(HelpersApi.CreateDataError(e.Message));
            }
        }
        /// <summary>
        /// VerifyCode by type generate
        /// </summary>
        /// <param name="user"></param>
        /// <param name="code"></param>
        /// <param name="typeGenerate"></param>
        /// <returns></returns>
        public static bool VerifyCodeSms(ApplicationUser user, string code, string typeGenerate)
        {
            try
            {
                var    secretSmsKey = SecretSmsKey.FromJson(user.ListSecretKeySms);
                string secret;
                switch (typeGenerate)
                {
                case Const.TypeGenerateChangePassword:
                    secret = secretSmsKey.ChangePassword;
                    break;

                case Const.TypeGenerateChangeOldPhoneNumber:
                    secret = secretSmsKey.ChangePhoneOldPhone;
                    break;

                case Const.TypeGenerateChangeNewPhoneNumber:
                    secret = secretSmsKey.ChangePhoneNewPhone;
                    break;

                case Const.TypeGenerateChangeConfirmPhoneNumber:
                    secret = secretSmsKey.ChangePhoneConfirmPhone;
                    break;

                case Const.TypeGenerateChangeTwoFactor:
                    secret = secretSmsKey.ChangeTwoFactor;
                    break;

                case Const.TypeGenerateLockAccount:
                    secret = secretSmsKey.LockAccount;
                    break;

                case Const.TypeGenerateUnlockAccount:
                    secret = secretSmsKey.UnlockAccount;
                    break;

                case Const.TypeGenerateAddPhoneNumber:
                    secret = secretSmsKey.AddPhoneNumber;
                    break;

                case Const.TypeGenerateAddLockScreen:
                    secret = secretSmsKey.AddLockScreen;
                    break;

                case Const.TypeGenerateLogin:
                    secret = secretSmsKey.Login;
                    break;

                default:
                    return(false);
                }

                if (string.IsNullOrEmpty(secret))
                {
                    return(false);
                }

                var authenticator = new TwoStepsAuthenticator.TimeAuthenticator();
                var isCheck       = authenticator.CheckCode(secret, code, user);
                return(isCheck);
            }
            catch (Exception e)
            {
                Logger.LogError("SecurityController ==>> VerifyCode: " + e.Message);
                return(false);
            }
        }