Exemple #1
0
        public async Task CanPasswordSignIn(bool isPersistent)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();

            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);

            SetupSignIn(context, auth, user.Id, isPersistent);
            var helper = SetupSignInManager(manager.Object, context);

            // Act
            var result = await helper.PasswordSignInAsync(user.UserName, "password", isPersistent, false);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user        = new PocoUser("test");
            var httpContext = new Mock <HttpContext>();

            await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/ true, async() =>
            {
                var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
                id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                var principal  = new ClaimsPrincipal(id);
                var properties = new AuthenticationProperties {
                    IssuedUtc = DateTimeOffset.UtcNow.AddSeconds(-1), IsPersistent = isPersistent
                };
                var ticket = new AuthenticationTicket(principal,
                                                      properties,
                                                      IdentityConstants.ApplicationScheme);

                var context = new CookieValidatePrincipalContext(httpContext.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
                {
                    HandlerType = typeof(NoopHandler)
                }.Build(), new CookieAuthenticationOptions(), ticket);
                Assert.NotNull(context.Properties);
                Assert.NotNull(context.Options);
                Assert.NotNull(context.Principal);
                await SecurityStampValidator.ValidatePrincipalAsync(context);
                Assert.NotNull(context.Principal);
            });
        }
Exemple #3
0
        public async Task PasswordSignInWorksWithNonTwoFactorStore()
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
            manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();

            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);

            SetupSignIn(context, auth);
            var helper = SetupSignInManager(manager.Object, context);

            // Act
            var result = await helper.PasswordSignInAsync(user.UserName, "password", false, false);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }
        public async Task CheckPasswordAlwaysResetLockoutWhenQuirked()
        {
            AppContext.SetSwitch("Microsoft.AspNetCore.Identity.CheckPasswordSignInAlwaysResetLockoutOnSuccess", true);

            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
            manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();

            var context = new DefaultHttpContext();
            var helper  = SetupSignInManager(manager.Object, context);

            // Act
            var result = await helper.CheckPasswordSignInAsync(user, "password", false);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
        }
Exemple #5
0
        public async Task CanExternalSignIn(bool isPersistent, bool supportsLockout)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            const string loginProvider = "login";
            const string providerKey   = "fookey";
            var          manager       = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
            if (supportsLockout)
            {
                manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            }
            manager.Setup(m => m.FindByLoginAsync(loginProvider, providerKey)).ReturnsAsync(user).Verifiable();

            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);
            var helper  = SetupSignInManager(manager.Object, context);

            SetupSignIn(context, auth, user.Id, isPersistent, loginProvider);

            // Act
            var result = await helper.ExternalLoginSignInAsync(loginProvider, providerKey, isPersistent);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }
Exemple #6
0
        public async Task GetExternalLoginInfoAsyncReturnsCorrectProviderDisplayName()
        {
            // Arrange
            var user = new PocoUser {
                Id = "foo", UserName = "******"
            };
            var userManager = SetupUserManager(user);
            var context     = new DefaultHttpContext();
            var identity    = new ClaimsIdentity();

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "bar"));
            var principal  = new ClaimsPrincipal(identity);
            var properties = new AuthenticationProperties();

            properties.Items["LoginProvider"] = "blah";
            var authResult = AuthenticateResult.Success(new AuthenticationTicket(principal, properties, "blah"));
            var auth       = MockAuth(context);

            auth.Setup(s => s.AuthenticateAsync(context, IdentityConstants.ExternalScheme)).ReturnsAsync(authResult);
            var schemeProvider = new Mock <IAuthenticationSchemeProvider>();
            var handler        = new Mock <IAuthenticationHandler>();

            schemeProvider.Setup(s => s.GetAllSchemesAsync())
            .ReturnsAsync(new[]
            {
                new AuthenticationScheme("blah", "Blah blah", handler.Object.GetType())
            });
            var signInManager = SetupSignInManager(userManager.Object, context, schemeProvider: schemeProvider.Object);

            // Act
            var externalLoginInfo = await signInManager.GetExternalLoginInfoAsync();

            // Assert
            Assert.Equal("Blah blah", externalLoginInfo.ProviderDisplayName);
        }
        public async Task CheckPasswordOnlyResetLockoutWhenTfaNotEnabled(bool tfaEnabled)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.SupportsUserTwoFactor).Returns(tfaEnabled).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();

            if (tfaEnabled)
            {
                manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
                manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).ReturnsAsync(new string[1] {
                    "Fake"
                }).Verifiable();
            }
            else
            {
                manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();
            }

            var context = new DefaultHttpContext();
            var helper  = SetupSignInManager(manager.Object, context);

            // Act
            var result = await helper.CheckPasswordSignInAsync(user, "password", false);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
        }
Exemple #8
0
        public async Task RememberClientStoresUserId()
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);
            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);
            var helper  = SetupSignInManager(manager.Object, context);

            auth.Setup(a => a.SignInAsync(
                           context,
                           IdentityConstants.TwoFactorRememberMeScheme,
                           It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id &&
                                                   i.Identities.First().AuthenticationType == IdentityConstants.TwoFactorRememberMeScheme),
                           It.Is <AuthenticationProperties>(v => v.IsPersistent == true))).Returns(Task.FromResult(0)).Verifiable();


            // Act
            await helper.RememberTwoFactorClientAsync(user);

            // Assert
            manager.Verify();
            auth.Verify();
        }
Exemple #9
0
        public async Task PasswordSignInFailsWithWrongPassword()
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "bogus")).ReturnsAsync(false).Verifiable();
            var context  = new Mock <HttpContext>();
            var logStore = new StringBuilder();
            var helper   = SetupSignInManager(manager.Object, context.Object, logStore);
            // Act
            var result = await helper.PasswordSignInAsync(user.UserName, "bogus", false, false);

            var checkResult = await helper.CheckPasswordSignInAsync(user, "bogus", false);

            // Assert
            Assert.False(result.Succeeded);
            Assert.False(checkResult.Succeeded);
            Assert.Contains($"User {user.Id} failed to provide the correct password.", logStore.ToString());
            manager.Verify();
            context.Verify();
        }
Exemple #10
0
        public async Task CheckPasswordSignInFailsWithWrongPasswordCanAccessFailedAndLockout()
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager   = SetupUserManager(user);
            var lockedout = false;

            manager.Setup(m => m.AccessFailedAsync(user)).Returns(() =>
            {
                lockedout = true;
                return(Task.FromResult(IdentityResult.Success));
            }).Verifiable();
            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).Returns(() => Task.FromResult(lockedout));
            manager.Setup(m => m.CheckPasswordAsync(user, "bogus")).ReturnsAsync(false).Verifiable();
            var context = new Mock <HttpContext>();
            var helper  = SetupSignInManager(manager.Object, context.Object);

            // Act
            var result = await helper.CheckPasswordSignInAsync(user, "bogus", true);

            // Assert
            Assert.False(result.Succeeded);
            Assert.True(result.IsLockedOut);
            manager.Verify();
        }
Exemple #11
0
        public async Task CheckPasswordSignInReturnsLockedOutWhenLockedOut()
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable();

            var context         = new Mock <HttpContext>();
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var roleManager     = MockHelpers.MockRoleManager <PocoRole>();
            var identityOptions = new IdentityOptions();
            var options         = new Mock <IOptions <IdentityOptions> >();

            options.Setup(a => a.Value).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory <PocoUser, PocoRole>(manager.Object, roleManager.Object, options.Object);
            var logStore      = new StringBuilder();
            var logger        = MockHelpers.MockILogger <SignInManager <PocoUser> >(logStore);
            var helper        = new SignInManager <PocoUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger.Object, new Mock <IAuthenticationSchemeProvider>().Object);

            // Act
            var result = await helper.CheckPasswordSignInAsync(user, "bogus", false);

            // Assert
            Assert.False(result.Succeeded);
            Assert.True(result.IsLockedOut);
            Assert.Contains($"User {user.Id} is currently locked out.", logStore.ToString());
            manager.Verify();
        }
Exemple #12
0
        public async Task CanRequireConfirmedPhoneNumberForPasswordSignIn(bool confirmed)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.IsPhoneNumberConfirmedAsync(user)).ReturnsAsync(confirmed).Verifiable();
            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);

            if (confirmed)
            {
                manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
                SetupSignIn(context, auth);
            }

            var identityOptions = new IdentityOptions();

            identityOptions.SignIn.RequireConfirmedPhoneNumber = true;
            var logStore = new StringBuilder();
            var helper   = SetupSignInManager(manager.Object, context, logStore, identityOptions);

            // Act
            var result = await helper.PasswordSignInAsync(user, "password", false, false);

            // Assert
            Assert.Equal(confirmed, result.Succeeded);
            Assert.NotEqual(confirmed, result.IsNotAllowed);
            Assert.Equal(confirmed, !logStore.ToString().Contains($"User {user.Id} cannot sign in without a confirmed phone number."));
            manager.Verify();
            auth.Verify();
        }
Exemple #13
0
        private static Mock <UserManager <PocoUser> > SetupUserManager(PocoUser user)
        {
            var manager = MockHelpers.MockUserManager <PocoUser>();

            manager.Setup(m => m.FindByNameAsync(user.UserName)).ReturnsAsync(user);
            manager.Setup(m => m.FindByIdAsync(user.Id)).ReturnsAsync(user);
            manager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id.ToString());
            manager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName);
            return(manager);
        }
Exemple #14
0
        public async Task CanResignIn(
            // Suppress warning that says theory methods should use all of their parameters.
            // See comments below about why this isn't used.
#pragma warning disable xUnit1026
            bool isPersistent,
#pragma warning restore xUnit1026
            bool externalLogin)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var context       = new DefaultHttpContext();
            var auth          = MockAuth(context);
            var loginProvider = "loginprovider";
            var id            = new ClaimsIdentity();

            if (externalLogin)
            {
                id.AddClaim(new Claim(ClaimTypes.AuthenticationMethod, loginProvider));
            }
            // REVIEW: auth changes we lost the ability to mock is persistent
            //var properties = new AuthenticationProperties { IsPersistent = isPersistent };
            var authResult = AuthenticateResult.NoResult();

            auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.ApplicationScheme))
            .Returns(Task.FromResult(authResult)).Verifiable();
            var manager       = SetupUserManager(user);
            var signInManager = new Mock <SignInManager <PocoUser> >(manager.Object,
                                                                     new HttpContextAccessor {
                HttpContext = context
            },
                                                                     new Mock <IUserClaimsPrincipalFactory <PocoUser> >().Object,
                                                                     null, null, new Mock <IAuthenticationSchemeProvider>().Object)
            {
                CallBase = true
            };

            //signInManager.Setup(s => s.SignInAsync(user, It.Is<AuthenticationProperties>(p => p.IsPersistent == isPersistent),
            //externalLogin? loginProvider : null)).Returns(Task.FromResult(0)).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, It.IsAny <AuthenticationProperties>(), null)).Returns(Task.FromResult(0)).Verifiable();
            signInManager.Object.Context = context;

            // Act
            await signInManager.Object.RefreshSignInAsync(user);

            // Assert
            auth.Verify();
            signInManager.Verify();
        }
        public async Task CanRequireConfirmedEmailForPasswordSignIn(bool confirmed)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.IsEmailConfirmedAsync(user)).ReturnsAsync(confirmed).Verifiable();
            if (confirmed)
            {
                manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
            }
            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);

            if (confirmed)
            {
                manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
                SetupSignIn(context, auth);
            }
            var identityOptions = new IdentityOptions();

            identityOptions.SignIn.RequireConfirmedEmail = true;
            var logger = new TestLogger <SignInManager <PocoUser> >();
            var helper = SetupSignInManager(manager.Object, context, logger, identityOptions);

            // Act
            var result = await helper.PasswordSignInAsync(user, "password", false, false);

            // Assert

            Assert.Equal(confirmed, result.Succeeded);
            Assert.NotEqual(confirmed, result.IsNotAllowed);

            var message = $"User {user.Id} cannot sign in without a confirmed email.";

            if (!confirmed)
            {
                Assert.Contains(message, logger.LogMessages);
            }
            else
            {
                Assert.DoesNotContain(message, logger.LogMessages);
            }

            manager.Verify();
            auth.Verify();
        }
Exemple #16
0
        public async Task CanTwoFactorRecoveryCodeSignIn(bool supportsLockout, bool externalLogin)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            const string bypassCode = "someCode";
            var          manager    = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
            manager.Setup(m => m.RedeemTwoFactorRecoveryCodeAsync(user, bypassCode)).ReturnsAsync(IdentityResult.Success).Verifiable();
            if (supportsLockout)
            {
                manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();
            }
            var context       = new DefaultHttpContext();
            var auth          = MockAuth(context);
            var helper        = SetupSignInManager(manager.Object, context);
            var twoFactorInfo = new SignInManager <PocoUser> .TwoFactorAuthenticationInfo {
                UserId = user.Id
            };
            var loginProvider = "loginprovider";
            var id            = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null);

            if (externalLogin)
            {
                auth.Setup(a => a.SignInAsync(context,
                                              IdentityConstants.ApplicationScheme,
                                              It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.AuthenticationMethod) == loginProvider &&
                                                                      i.FindFirstValue(ClaimTypes.NameIdentifier) == user.Id),
                                              It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
                auth.Setup(a => a.SignOutAsync(context, IdentityConstants.ExternalScheme, It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
                auth.Setup(a => a.SignOutAsync(context, IdentityConstants.TwoFactorUserIdScheme, It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
            }
            else
            {
                SetupSignIn(context, auth, user.Id);
            }
            auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.TwoFactorUserIdScheme))
            .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(id, null, IdentityConstants.TwoFactorUserIdScheme))).Verifiable();

            // Act
            var result = await helper.TwoFactorRecoveryCodeSignInAsync(bypassCode);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }
        public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
        {
            var user            = new PocoUser("test");
            var httpContext     = new Mock <HttpContext>();
            var userManager     = MockHelpers.MockUserManager <PocoUser>();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var claimsManager = new Mock <IUserClaimsPrincipalFactory <PocoUser> >();
            var options       = new Mock <IOptions <SecurityStampValidatorOptions> >();

            options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.FromDays(1)
            });
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock <SignInManager <PocoUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).Throws(new Exception("Shouldn't be called"));
            signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called"));
            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(signInManager.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <PocoUser>(options.Object, signInManager.Object, new SystemClock()));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id),
                                                  new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow
            },
                                                  IdentityConstants.ApplicationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
            {
                HandlerType = typeof(NoopHandler)
            }.Build(), new CookieAuthenticationOptions(), ticket);

            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await SecurityStampValidator.ValidatePrincipalAsync(context);

            Assert.NotNull(context.Principal);
        }
Exemple #18
0
        public async Task ValidateFailsWithTooShortUserNames(string input)
        {
            // Setup
            var manager   = MockHelpers.TestUserManager(new NoopUserStore());
            var validator = new UserValidator <PocoUser>();
            var user      = new PocoUser {
                UserName = input
            };

            // Act
            var result = await validator.ValidateAsync(manager, user);

            // Assert
            IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().InvalidUserName(input));
        }
Exemple #19
0
        public async Task CanTwoFactorAuthenticatorSignIn(string providerName, bool isPersistent, bool rememberClient)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            const string code    = "3123";
            var          manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.VerifyTwoFactorTokenAsync(user, providerName ?? TokenOptions.DefaultAuthenticatorProvider, code)).ReturnsAsync(true).Verifiable();
            manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();

            var context       = new DefaultHttpContext();
            var auth          = MockAuth(context);
            var helper        = SetupSignInManager(manager.Object, context);
            var twoFactorInfo = new SignInManager <PocoUser> .TwoFactorAuthenticationInfo {
                UserId = user.Id
            };

            if (providerName != null)
            {
                helper.Options.Tokens.AuthenticatorTokenProvider = providerName;
            }
            var id = helper.StoreTwoFactorInfo(user.Id, null);

            SetupSignIn(context, auth, user.Id, isPersistent);
            auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.TwoFactorUserIdScheme))
            .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(id, null, IdentityConstants.TwoFactorUserIdScheme))).Verifiable();
            if (rememberClient)
            {
                auth.Setup(a => a.SignInAsync(context,
                                              IdentityConstants.TwoFactorRememberMeScheme,
                                              It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id &&
                                                                      i.Identities.First().AuthenticationType == IdentityConstants.TwoFactorRememberMeScheme),
                                              It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
            }

            // Act
            var result = await helper.TwoFactorAuthenticatorSignInAsync(code, isPersistent, rememberClient);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }
Exemple #20
0
        public async Task ExternalSignInRequiresVerificationIfNotBypassed(bool bypass)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            const string loginProvider = "login";
            const string providerKey   = "fookey";
            var          manager       = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(false).Verifiable();
            manager.Setup(m => m.FindByLoginAsync(loginProvider, providerKey)).ReturnsAsync(user).Verifiable();
            if (!bypass)
            {
                IList <string> providers = new List <string>();
                providers.Add("PhoneNumber");
                manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).Returns(Task.FromResult(providers)).Verifiable();
                manager.Setup(m => m.SupportsUserTwoFactor).Returns(true).Verifiable();
                manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
            }
            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);
            var helper  = SetupSignInManager(manager.Object, context);

            if (bypass)
            {
                SetupSignIn(context, auth, user.Id, false, loginProvider);
            }
            else
            {
                auth.Setup(a => a.SignInAsync(context, IdentityConstants.TwoFactorUserIdScheme,
                                              It.Is <ClaimsPrincipal>(id => id.FindFirstValue(ClaimTypes.Name) == user.Id),
                                              It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
            }

            // Act
            var result = await helper.ExternalLoginSignInAsync(loginProvider, providerKey, isPersistent : false, bypassTwoFactor : bypass);

            // Assert
            Assert.Equal(bypass, result.Succeeded);
            Assert.Equal(!bypass, result.RequiresTwoFactor);
            manager.Verify();
            auth.Verify();
        }
        private async Task RunApplicationCookieTest(PocoUser user, Mock <HttpContext> httpContext, bool shouldStampValidate, Func <Task> testCode)
        {
            var userManager     = MockHelpers.MockUserManager <PocoUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <PocoUser> >();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var options = new Mock <IOptions <SecurityStampValidatorOptions> >();

            options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.Zero
            });
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock <SignInManager <PocoUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object, new DefaultUserConfirmation <PocoUser>());

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default).Verifiable();
Exemple #22
0
        public async Task PasswordSignInRequiresVerification(bool supportsLockout)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
            if (supportsLockout)
            {
                manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            }
            IList <string> providers = new List <string>();

            providers.Add("PhoneNumber");
            manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).Returns(Task.FromResult(providers)).Verifiable();
            manager.Setup(m => m.SupportsUserTwoFactor).Returns(true).Verifiable();
            manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
            if (supportsLockout)
            {
                manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();
            }
            var context = new DefaultHttpContext();
            var helper  = SetupSignInManager(manager.Object, context);
            var auth    = MockAuth(context);

            auth.Setup(a => a.SignInAsync(context, IdentityConstants.TwoFactorUserIdScheme,
                                          It.Is <ClaimsPrincipal>(id => id.FindFirstValue(ClaimTypes.Name) == user.Id),
                                          It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();

            // Act
            var result = await helper.PasswordSignInAsync(user.UserName, "password", false, false);

            // Assert
            Assert.False(result.Succeeded);
            Assert.True(result.RequiresTwoFactor);
            manager.Verify();
            auth.Verify();
        }
        private async Task RunApplicationCookieTest(PocoUser user, Mock <HttpContext> httpContext, bool shouldStampValidate, Func <Task> testCode)
        {
            var userManager     = MockHelpers.MockUserManager <PocoUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <PocoUser> >();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var options = new Mock <IOptions <SecurityStampValidatorOptions> >();

            options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.Zero
            });
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock <SignInManager <PocoUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default(PocoUser)).Verifiable();

            if (shouldStampValidate)
            {
                var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
                id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                var principal = new ClaimsPrincipal(id);
                signInManager.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable();
            }

            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(signInManager.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <PocoUser>(options.Object, signInManager.Object, new SystemClock()));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());

            await testCode.Invoke();

            signInManager.VerifyAll();
        }
Exemple #24
0
        public async Task DefaultAlphaNumericOnlyUserNameValidation(string userName, bool expectSuccess)
        {
            // Setup
            var manager   = MockHelpers.TestUserManager(new NoopUserStore());
            var validator = new UserValidator <PocoUser>();
            var user      = new PocoUser {
                UserName = userName
            };

            // Act
            var result = await validator.ValidateAsync(manager, user);

            // Assert
            if (expectSuccess)
            {
                IdentityResultAssert.IsSuccess(result);
            }
            else
            {
                IdentityResultAssert.IsFailure(result);
            }
        }
        private async Task RunRememberClientCookieTest(bool shouldStampValidate, bool validationSuccess)
        {
            var user        = new PocoUser("test");
            var httpContext = new Mock <HttpContext>();
            var userManager = MockHelpers.MockUserManager <PocoUser>();

            userManager.Setup(u => u.GetUserIdAsync(user)).ReturnsAsync(user.Id).Verifiable();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <PocoUser> >();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var options = new Mock <IOptions <SecurityStampValidatorOptions> >();

            options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.Zero
            });
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock <SignInManager <PocoUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object);

            signInManager.Setup(s => s.ValidateTwoFactorSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default).Verifiable();
Exemple #26
0
        public async Task RememberBrowserSkipsTwoFactorVerificationSignIn(bool isPersistent)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager = SetupUserManager(user);

            manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
            IList <string> providers = new List <string>();

            providers.Add("PhoneNumber");
            manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).Returns(Task.FromResult(providers)).Verifiable();
            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.SupportsUserTwoFactor).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.CheckPasswordAsync(user, "password")).ReturnsAsync(true).Verifiable();
            var context = new DefaultHttpContext();
            var auth    = MockAuth(context);

            SetupSignIn(context, auth);
            var id = new ClaimsIdentity(IdentityConstants.TwoFactorRememberMeScheme);

            id.AddClaim(new Claim(ClaimTypes.Name, user.Id));
            auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.TwoFactorRememberMeScheme))
            .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(id), null, IdentityConstants.TwoFactorRememberMeScheme))).Verifiable();
            var helper = SetupSignInManager(manager.Object, context);

            // Act
            var result = await helper.PasswordSignInAsync(user.UserName, "password", isPersistent, false);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }
Exemple #27
0
        public async Task CanAllowNonAlphaNumericUserName(string userName, bool expectSuccess)
        {
            // Setup
            var manager = MockHelpers.TestUserManager(new NoopUserStore());

            manager.Options.User.AllowedUserNameCharacters = null;
            var validator = new UserValidator <PocoUser>();
            var user      = new PocoUser {
                UserName = userName
            };

            // Act
            var result = await validator.ValidateAsync(manager, user);

            // Assert
            if (expectSuccess)
            {
                IdentityResultAssert.IsSuccess(result);
            }
            else
            {
                IdentityResultAssert.IsFailure(result);
            }
        }
Exemple #28
0
        public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims, bool supportsUserEmail)
        {
            // Setup
            var userManager = MockHelpers.MockUserManager <PocoUser>();
            var roleManager = MockHelpers.MockRoleManager <PocoRole>();
            var user        = new PocoUser {
                UserName = "******", Email = "*****@*****.**"
            };

            userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims);
            userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles);
            userManager.Setup(m => m.SupportsUserEmail).Returns(supportsUserEmail);
            userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id);
            userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName);
            if (supportsUserEmail)
            {
                userManager.Setup(m => m.GetEmailAsync(user)).ReturnsAsync(user.Email);
            }
            var roleClaims = new[] { "Admin", "Local" };

            if (supportRoles)
            {
                userManager.Setup(m => m.GetRolesAsync(user)).ReturnsAsync(roleClaims);
                roleManager.Setup(m => m.SupportsRoleClaims).Returns(supportRoleClaims);
            }
            var userClaims = new[] { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") };

            if (supportClaims)
            {
                userManager.Setup(m => m.GetClaimsAsync(user)).ReturnsAsync(userClaims);
            }
            userManager.Object.Options = new IdentityOptions();

            var admin = new PocoRole()
            {
                Name = "Admin"
            };
            var local = new PocoRole()
            {
                Name = "Local"
            };
            var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") };
            var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") };

            if (supportRoleClaims)
            {
                roleManager.Setup(m => m.FindByNameAsync("Admin")).ReturnsAsync(admin);
                roleManager.Setup(m => m.FindByNameAsync("Local")).ReturnsAsync(local);
                roleManager.Setup(m => m.GetClaimsAsync(admin)).ReturnsAsync(adminClaims);
                roleManager.Setup(m => m.GetClaimsAsync(local)).ReturnsAsync(localClaims);
            }

            var options         = new Mock <IOptions <IdentityOptions> >();
            var identityOptions = new IdentityOptions();

            options.Setup(a => a.Value).Returns(identityOptions);
            var factory = new UserClaimsPrincipalFactory <PocoUser, PocoRole>(userManager.Object, roleManager.Object, options.Object);

            // Act
            var principal = await factory.CreateAsync(user);

            var identity = principal.Identities.First();

            // Assert
            var manager = userManager.Object;

            Assert.NotNull(identity);
            Assert.Single(principal.Identities);
            Assert.Equal(IdentityConstants.ApplicationScheme, identity.AuthenticationType);
            var claims = identity.Claims.ToList();

            Assert.NotNull(claims);
            Assert.Contains(
                claims, c => c.Type == manager.Options.ClaimsIdentity.UserNameClaimType && c.Value == user.UserName);
            Assert.Contains(claims, c => c.Type == manager.Options.ClaimsIdentity.UserIdClaimType && c.Value == user.Id);
            Assert.Equal(supportsUserEmail, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.EmailClaimType && c.Value == user.Email));
            Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Admin"));
            Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Local"));
            foreach (var cl in userClaims)
            {
                Assert.Equal(supportClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
            foreach (var cl in adminClaims)
            {
                Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
            foreach (var cl in localClaims)
            {
                Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
            userManager.VerifyAll();
            roleManager.VerifyAll();
        }
Exemple #29
0
        public async Task CanTwoFactorSignIn(bool isPersistent, bool supportsLockout, bool externalLogin, bool rememberClient)
        {
            // Setup
            var user = new PocoUser {
                UserName = "******"
            };
            var manager  = SetupUserManager(user);
            var provider = "twofactorprovider";
            var code     = "123456";

            manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
            if (supportsLockout)
            {
                manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
                manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable();
            }
            manager.Setup(m => m.VerifyTwoFactorTokenAsync(user, provider, code)).ReturnsAsync(true).Verifiable();
            var context       = new DefaultHttpContext();
            var auth          = MockAuth(context);
            var helper        = SetupSignInManager(manager.Object, context);
            var twoFactorInfo = new SignInManager <PocoUser> .TwoFactorAuthenticationInfo {
                UserId = user.Id
            };
            var loginProvider = "loginprovider";
            var id            = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null);

            if (externalLogin)
            {
                auth.Setup(a => a.SignInAsync(context,
                                              IdentityConstants.ApplicationScheme,
                                              It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.AuthenticationMethod) == loginProvider &&
                                                                      i.FindFirstValue(ClaimTypes.NameIdentifier) == user.Id),
                                              It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
                // REVIEW: restore ability to test is persistent
                //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Verifiable();
                auth.Setup(a => a.SignOutAsync(context, IdentityConstants.ExternalScheme, It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
                auth.Setup(a => a.SignOutAsync(context, IdentityConstants.TwoFactorUserIdScheme, It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
            }
            else
            {
                SetupSignIn(context, auth, user.Id);
            }
            if (rememberClient)
            {
                auth.Setup(a => a.SignInAsync(context,
                                              IdentityConstants.TwoFactorRememberMeScheme,
                                              It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id &&
                                                                      i.Identities.First().AuthenticationType == IdentityConstants.TwoFactorRememberMeScheme),
                                              It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
                //It.Is<AuthenticationProperties>(v => v.IsPersistent == true))).Returns(Task.FromResult(0)).Verifiable();
            }
            auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.TwoFactorUserIdScheme))
            .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(id, null, IdentityConstants.TwoFactorUserIdScheme))).Verifiable();

            // Act
            var result = await helper.TwoFactorSignInAsync(provider, code, isPersistent, rememberClient);

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }