Beispiel #1
0
        public void TestCreateIdentityErrors()
        {
            const string expectedErrorMsg = "Test fail";

            //setup mocks
            _mockUserManager.Setup(x => x.CreateAsync(It.IsAny <TestAppUser>(), It.IsAny <string>()))
            .Returns(Task.FromResult(IdentityResult.Failed(new IdentityError {
                Description = expectedErrorMsg
            })));

            //setup user
            var testUserCorrect = new TestAppUser
            {
                Email     = "*****@*****.**",
                UserName  = "******",
                FirstName = "Test"
            };

            //run method
            var task   = _userRepository.Create(testUserCorrect, "Aa1234");
            var result = task.Result;

            Assert.False(result.Succeeded);
            Assert.Equal(1, result.Errors.Count);
            Assert.Null(result.Jwt);
            Assert.Null(result.RefreshToken);
            Assert.Equal(expectedErrorMsg, result.Errors[0].Message);
            _mockDefaultJwtHandler.Verify(e => e.Generate(null), Times.Never());
        }
Beispiel #2
0
        public async Task TestRefreshTokenNoEmailClaim()
        {
            //setup user and list of users.
            var testUser = new TestAppUser
            {
                Email         = "*****@*****.**",
                UserName      = "******",
                FirstName     = "Test",
                RefreshTokens = new List <RefreshToken> {
                    new RefreshToken {
                        Token      = "refresh",
                        Expiration = new DateTimeOffset(DateTime.Now.AddDays(100)).ToUnixTimeSeconds()
                    }
                }
            };
            var listOfUsers = new List <TestAppUser> {
                testUser
            };

            //setup mocks
            var mockDbSet = listOfUsers.AsQueryable().BuildMockDbSet();

            _mockUserManager.Setup(x => x.Users).Returns(mockDbSet.Object);
            var principal = new ClaimsPrincipal();

            _mockDefaultJwtHandler.Setup(x => x.GetPrincipalFromExpiredToken(It.IsAny <string>()))
            .Returns(principal);

            await Assert.ThrowsAsync <NullReferenceException>(() => _userRepository.RefreshToken("jwt", "refresh"));

            _mockUserManager.Verify(e => e.UpdateAsync(It.IsAny <TestAppUser>()), Times.Never);
            _mockDefaultJwtHandler.Verify(e => e.Generate(It.IsAny <List <Claim> >()), Times.Never);
        }
Beispiel #3
0
        public void TestCreateCorrectInput()
        {
            //setup mocks
            _mockUserManager.Setup(x => x.CreateAsync(It.IsAny <TestAppUser>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new IdentityResult()));
            _mockUserManager.Setup(x => x.UpdateAsync(It.IsAny <TestAppUser>()))
            .Verifiable();
            const string expectedToken = "test_token";

            _mockDefaultJwtHandler.Setup(x => x.Generate(It.IsAny <List <Claim> >()))
            .Returns(expectedToken);

            //setup result
            var testUserCorrect = new TestAppUser
            {
                Email     = "*****@*****.**",
                UserName  = "******",
                FirstName = "Test"
            };

            var task   = _userRepository.Create(testUserCorrect, "Aa1234");
            var result = task.Result;

            Assert.True(result.Succeeded);
            Assert.Empty(result.Errors);
            Assert.NotNull(result.RefreshToken);
            Assert.Equal(expectedToken, result.Jwt);
            _mockUserManager.Verify(e => e.UpdateAsync(It.IsAny <TestAppUser>()), Times.Once);
        }
Beispiel #4
0
        public void TestAuthenticateCheckPasswordFail()
        {
            //setup mocks
            _mockUserManager.Setup(x => x.CheckPasswordAsync(It.IsAny <TestAppUser>(), It.IsAny <string>()))
            .Returns(Task.FromResult(false));

            //setup user
            var testUserCorrect = new TestAppUser
            {
                Email     = "*****@*****.**",
                UserName  = "******",
                FirstName = "Test"
            };

            //setup expected
            const string expectedErrorMsg = "Invalid credentials supplied";

            //run method
            var task   = _userRepository.Authenticate(testUserCorrect, "Aa1234");
            var result = task.Result;

            Assert.False(result.Succeeded);
            Assert.Equal(1, result.Errors.Count);
            Assert.Null(result.Jwt);
            Assert.Null(result.RefreshToken);
            Assert.Equal(expectedErrorMsg, result.Errors[0].Message);
            _mockUserManager.Verify(e => e.UpdateAsync(It.IsAny <TestAppUser>()), Times.Never);
        }
Beispiel #5
0
        [InlineData(null, 10)]             //null token
        public void TestRefreshTokenInvalid(string refreshToken, int daysToAdd)
        {
            //setup user and list of users.
            var testUser = new TestAppUser
            {
                Email         = "*****@*****.**",
                UserName      = "******",
                FirstName     = "Test",
                RefreshTokens = new List <RefreshToken> {
                    new RefreshToken {
                        Token      = "refresh",
                        Expiration = new DateTimeOffset(DateTime.Now.AddDays(daysToAdd)).ToUnixTimeSeconds()
                    }
                }
            };
            var listOfUsers = new List <TestAppUser> {
                testUser
            };

            //setup expected
            const string expectedErrorMsg = "Invalid token";

            //setup mocks
            var mockDbSet = listOfUsers.AsQueryable().BuildMockDbSet();

            _mockUserManager.Setup(x => x.Users).Returns(mockDbSet.Object);
            var principal = new ClaimsPrincipal();

            principal.AddIdentity(new ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Email, "*****@*****.**")
            }));
            _mockDefaultJwtHandler.Setup(x => x.GetPrincipalFromExpiredToken(It.IsAny <string>()))
            .Returns(principal);

            //run method
            var task   = _userRepository.RefreshToken("jwt", refreshToken);
            var result = task.Result;

            Assert.False(result.Succeeded);
            Assert.Equal(1, result.Errors.Count);
            Assert.Null(result.Jwt);
            Assert.Null(result.RefreshToken);
            Assert.Equal(expectedErrorMsg, result.Errors[0].Message);
            _mockUserManager.Verify(e => e.UpdateAsync(It.IsAny <TestAppUser>()), Times.Never);
            _mockDefaultJwtHandler.Verify(e => e.Generate(It.IsAny <List <Claim> >()), Times.Never);
        }
Beispiel #6
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(TestAppUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

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

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new TestAppUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Beispiel #8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new TestAppUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }