Beispiel #1
0
        public async Task <IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            returnUrl = returnUrl ?? Url.Content("~/");

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                throw new InvalidOperationException($"Unable to load two-factor authentication user.");
            }

            var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var result = await _signInManager.RespondToTwoFactorChallengeAsync(authenticatorCode, rememberMe, Input.RememberMachine);

            if (result.Succeeded)
            {
                _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.UserID);
                return(LocalRedirect(returnUrl));
            }
            else
            {
                _logger.LogWarning("Invalid 2FA code entered for user with ID '{UserId}'.", user.UserID);
                ModelState.AddModelError(string.Empty, "Invalid 2FA code.");
                return(Page());
            }
        }
        public async void Test_GivenAUserWith2FA_WhenRespondToTwoFactorChallengeWithCorrectCode_ThenReturnSigninResultSuccess()
        {
            var cognitoUser = GetCognitoUser();
            var context     = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme);

            contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable();

            var authFlowResponse = new AuthFlowResponse("sessionId", null, ChallengeNameType.SMS_MFA, null, null);

            userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny <string>())).Returns(Task.FromResult(cognitoUser)).Verifiable();
            userManagerMock.Setup(mock => mock.RespondToTwoFactorChallengeAsync(It.IsAny <CognitoUser>(), It.IsAny <string>(), It.IsAny <ChallengeNameType>(), It.IsAny <string>()))
            .Returns(Task.FromResult(authFlowResponse))
            .Callback(() => cognitoUser.SessionTokens = new CognitoUserSession("idToken", "accessToken", "refreshToken", DateTime.Now, DateTime.Now.AddDays(1))).Verifiable();
            userManagerMock.Setup(mock => mock.GetClaimsAsync(It.IsAny <CognitoUser>())).Returns(Task.FromResult(new List <Claim>() as IList <Claim>)).Verifiable();
            userManagerMock.Setup(mock => mock.GetRolesAsync(It.IsAny <CognitoUser>())).Returns(Task.FromResult(new List <string>() as IList <string>)).Verifiable();

            var output = await signinManager.RespondToTwoFactorChallengeAsync("2FACODE", true, false).ConfigureAwait(false);

            Assert.Equal(SignInResult.Success, output);
            contextAccessorMock.Verify();
            userManagerMock.Verify();
        }