Пример #1
0
        public async Task <IActionResult> TwoFactorAuth(AuthenticatorViewModel authenticatorViewModel)
        {
            switch (authenticatorViewModel.TwoFactorType)
            {
            case TwoFactor.None:
                CurrentUser.TwoFactorEnabled = false;
                CurrentUser.TwoFactor        = (sbyte)TwoFactor.None;
                TempData["message"]          = "iki adımlı kimlik doğrulama tipiniz hiç biri olarak belirlenmiştir";

                break;

            case TwoFactor.MicrosoftGoogle:

                return(RedirectToAction("TwoFactorWithAuthenticator"));

            case TwoFactor.Email:

                CurrentUser.TwoFactorEnabled = true;
                CurrentUser.TwoFactor        = (sbyte)TwoFactor.Email;
                TempData["message"]          = "iki adımlı kimlik doğrulama tipiniz email olarak belirlenmiştir";


                break;

            default:
                break;
            }

            await _userManager.UpdateAsync(CurrentUser);

            return(View(authenticatorViewModel));
        }
Пример #2
0
        public async Task <IActionResult> TwoFactorWithAuthenticator(AuthenticatorViewModel authenticatorViewModel)
        {
            var verificationCode = authenticatorViewModel.VerificationCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var is2FATokenValid = await _userManager.VerifyTwoFactorTokenAsync(CurrentUser, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);


            if (is2FATokenValid)
            {
                CurrentUser.TwoFactorEnabled = true;
                CurrentUser.TwoFactor        = (sbyte)TwoFactor.MicrosoftGoogle;

                var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(CurrentUser, 5);

                TempData["recoveryCodes"] = recoveryCodes;
                TempData["message"]       = "iki adımlı kimlik doğrulama tipiniz Microsoft/Google olarak belirlenmiştir";

                return(RedirectToAction("TwoFactorAuth"));
            }
            else
            {
                ModelState.AddModelError("", "Girdiğiniz Doğrulama Kodu Yanlıştır");

                return(View(authenticatorViewModel));
            }
        }
Пример #3
0
        public async Task <AuthenticatorViewModel> GetAuthenticatorForUser(string userId)
        {
            var user = await _applicationUserManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(new AuthenticatorViewModel());
            }
            var model = new AuthenticatorViewModel();

            await LoadSharedKeyAndQrCodeUriAsync(user, model);

            return(model);
        }
Пример #4
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(AppUser user, AuthenticatorViewModel model)
        {
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            model.SharedKey        = FormatKey(unformattedKey);
            model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey);
        }
Пример #5
0
        public async Task <IActionResult> TwoFactorWithAuthenticator()
        {
            string unFormattedKey = await UserManager.GetAuthenticatorKeyAsync(CurrentUser);

            if (string.IsNullOrEmpty(unFormattedKey))
            {
                await UserManager.ResetAuthenticatorKeyAsync(CurrentUser);

                unFormattedKey = await UserManager.GetAuthenticatorKeyAsync(CurrentUser);
            }
            AuthenticatorViewModel authenticatorViewModel = new AuthenticatorViewModel()
            {
                SharedKey        = unFormattedKey,
                AuthenticatorUri = _twoFactorService.GenerateQRCodeUri(CurrentUser.Email, unFormattedKey)
            };

            return(View(authenticatorViewModel));
        }
Пример #6
0
        public async Task <IActionResult> TwoFactorAuthentication(AuthenticatorViewModel authenticatorViewModel)
        {
            switch (authenticatorViewModel.TwoFactorTypes)
            {
            case TwoFactorAuthTypes.None:
                CurrentUser.TwoFactorEnabled     = false;
                TempData["TwoFactorTypeMessage"] = "İki adımlı kimlik doğrulama aktif değildir.";
                break;

            case TwoFactorAuthTypes.SMS:
                if (string.IsNullOrEmpty(CurrentUser.PhoneNumber))
                {
                    CurrentUser.TwoFactorEnabled = false;
                    ViewBag.Message = "Telefon numaranız sistemde kayıtlı olmadığı için SMS ile doğrulama yapamazsınız.";
                }
                else
                {
                    CurrentUser.TwoFactorEnabled     = true;
                    TempData["TwoFactorTypeMessage"] = "İki adımlı kimlik doğrulama SMS olarak aktif hale getirilmiştir.";
                }
                break;

            case TwoFactorAuthTypes.Email:
                CurrentUser.TwoFactorEnabled     = true;
                TempData["TwoFactorTypeMessage"] = "İki adımlı kimlik doğrulama email olarak aktif hale getirilmiştir.";
                break;

            case TwoFactorAuthTypes.MicrosoftGoogle:
                return(RedirectToAction("TwoFactorWithAuthenticator"));

            default:
                break;
            }
            CurrentUser.TwoFactorAuthType = (sbyte)authenticatorViewModel.TwoFactorTypes;
            IdentityResult result = await UserManager.UpdateAsync(CurrentUser);

            if (!result.Succeeded)
            {
                AddModelError(result);
            }
            return(View(authenticatorViewModel));
        }
Пример #7
0
        public async Task <IActionResult> Authenticator()
        {
            // Retrieve the user info
            var user = await _userManager.GetUserAsync(User);

            if (user is null)
            {
                //var userId = _userManager.GetUserId(User);
                var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                _logger.LogWarning("Unable to load user with ID {UserId}.", userId);
                return(BadRequest(new ApiBadRequestResponse(ModelState, "Unable to load user profile for authenticator.")));
            }

            // Generate SharedKey and QR Code
            var model = new AuthenticatorViewModel();

            await LoadSharedKeyAndQrCodeUriAsync(user, model);

            return(Ok(new ApiOkResponse(model).Result));
        }
Пример #8
0
        public async Task <IActionResult> TwoFactorWithAuthenticator(AuthenticatorViewModel authenticatorViewModel)
        {
            var verificationCode = authenticatorViewModel.VerificationCode.Replace(" ", string.Empty).Replace("-", string.Empty).Replace("_", string.Empty);

            bool is2FATokenValid = await UserManager.VerifyTwoFactorTokenAsync(CurrentUser, UserManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);

            if (is2FATokenValid)
            {
                CurrentUser.TwoFactorEnabled  = true;
                CurrentUser.TwoFactorAuthType = (sbyte)TwoFactorAuthTypes.MicrosoftGoogle;
                var recoveryCodes = await UserManager.GenerateNewTwoFactorRecoveryCodesAsync(CurrentUser, 5);

                TempData["TwoFactorRecoveryCodes"] = recoveryCodes;
                TempData["TwoFactorTypeMessage"]   = "İki adımlı doğrulama başarı ile sağlanmıştır.";
                return(RedirectToAction("TwoFactorAuthentication"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Girilen doğrulama kodu yanlıştır.");
            }
            return(View());
        }
Пример #9
0
        public async Task <IActionResult> Authenticator([FromBody] AuthenticatorViewModel model)
        {
            // Retrieve the user info
            var user = await _userManager.GetUserAsync(User);

            if (user is null)
            {
                //var userId = _userManager.GetUserId(User);
                var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                _logger.LogWarning("Unable to load user with ID {UserId}.", userId);
                return(BadRequest(new ApiBadRequestResponse(ModelState, "Unable to load user profile for authenticator.")));
            }

            // Strip spaces and hypens
            var pin = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

            var valid = await _userManager.VerifyTwoFactorTokenAsync(user, _userManager.Options.Tokens.AuthenticatorTokenProvider, pin);

            if (!valid)
            {
                _logger.LogInformation("User with ID {UserId} used an invalid verification code.", user.Id);
                // TODO: Return the AuthenticatorViewModel with the error
                return(BadRequest(new ApiBadRequestResponse(Errors.AddErrorToModelState("verification_failure", "Verification code is invalid.", ModelState))));
            }

            await _userManager.SetTwoFactorEnabledAsync(user, true); // Does it stores any info regarding when it was activated? And if so, can we retrieve it?

            _logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);

            // Below could be skipped and instead retrieve the code when GET api/profile/authenticator/codes
            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);

            TempData[RecoveryCodesKey] = recoveryCodes.ToArray();

            return(Ok());
        }
Пример #10
0
        public async Task <ActionResult> Authenticator(AuthenticatorViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var loginViewModel = TempData.Peek("LoginAuthenticatorViewModel") as LoginAuthenticatorViewModel;

            if (loginViewModel == null)
            {
                return(RedirectToAction("Login"));
            }

            //var secretKey = Base32Encoder.FromBase32String(SecretKey);
            var secretKey = Base32Encoder.FromBase32String(loginViewModel.AuthenticatorSecrete);

            var currentInterval = GoogleAuthenticator.CurrentInterval;

            if (GoogleAuthenticator.GeneratePin(secretKey, currentInterval) == model.Factor)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(loginViewModel.Email, loginViewModel.Password, loginViewModel.RememberMe, false);

                switch (result)
                {
                case SignInStatus.Success:
                {
                    TempData.Remove("LoginViewModel");
                    return(RedirectToLocal(returnUrl));
                }

                case SignInStatus.LockedOut:
                {
                    TempData.Remove("LoginViewModel");
                    return(View("Lockout"));
                }

                case SignInStatus.RequiresVerification:
                {
                    TempData.Remove("LoginViewModel");
                    return(RedirectToAction("SendCode", new
                        {
                            ReturnUrl = returnUrl,
                            loginViewModel.RememberMe
                        }));
                }

                case SignInStatus.Failure:
                default:
                {
                    ModelState.AddModelError("", "Invalid authenticator attempt.");
                    return(View(model));
                }
                }
            }

            ModelState.AddModelError("", "Invalid authenticator attempt.");
            return(View(model));
        }
Пример #11
0
        public async Task<ActionResult> Authenticator(AuthenticatorViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var loginViewModel = TempData.Peek("LoginAuthenticatorViewModel") as LoginAuthenticatorViewModel;
            if (loginViewModel == null)
            {
                return RedirectToAction("Login");
            }

            //var secretKey = Base32Encoder.FromBase32String(SecretKey);
            var secretKey = Base32Encoder.FromBase32String(loginViewModel.AuthenticatorSecrete);

            var currentInterval = GoogleAuthenticator.CurrentInterval;

            if (GoogleAuthenticator.GeneratePin(secretKey, currentInterval) == model.Factor)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(loginViewModel.Email, loginViewModel.Password, loginViewModel.RememberMe, false);
                switch (result)
                {
                    case SignInStatus.Success:
                    {
                        TempData.Remove("LoginViewModel");
                        return RedirectToLocal(returnUrl);
                    }
                    case SignInStatus.LockedOut:
                    {
                        TempData.Remove("LoginViewModel");
                        return View("Lockout");
                    }
                    case SignInStatus.RequiresVerification:
                    {
                        TempData.Remove("LoginViewModel");
                        return RedirectToAction("SendCode", new
                        {
                            ReturnUrl = returnUrl,
                            loginViewModel.RememberMe
                        });
                    }
                    case SignInStatus.Failure:
                    default:
                    {
                        ModelState.AddModelError("", "Invalid authenticator attempt.");
                        return View(model);
                    }
                }
            }

            ModelState.AddModelError("", "Invalid authenticator attempt.");
            return View(model);
        }
Пример #12
0
 public AuthenticatorView()
 {
     InitializeComponent();
     BindingContext = new AuthenticatorViewModel(Navigation);
 }