Пример #1
0
        private static Mock <UserManager <TestUser> > SetupUserManager(TestUser user)
        {
            var manager = MockHelpers.MockUserManager <TestUser>();

            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);
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user            = new TestUser("test");
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            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 httpContext     = new Mock <HttpContext>();
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            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 signInManager = new Mock <SignInManager <TestUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(user).Verifiable();
            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 <TestUser>(options.Object, signInManager.Object, new SystemClock()));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());

            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);
            signInManager.VerifyAll();
        }
Пример #3
0
        public void ConstructorNullChecks()
        {
            Assert.Throws <ArgumentNullException>("userManager", () => new SignInManager <TestUser>(null, null, null, null, null, null));
            var userManager = MockHelpers.MockUserManager <TestUser>().Object;

            Assert.Throws <ArgumentNullException>("contextAccessor", () => new SignInManager <TestUser>(userManager, null, null, null, null, null));
            var contextAccessor = new Mock <IHttpContextAccessor>();
            var context         = new Mock <HttpContext>();

            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            Assert.Throws <ArgumentNullException>("claimsFactory", () => new SignInManager <TestUser>(userManager, contextAccessor.Object, null, null, null, null));
        }
        public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
        {
            var user            = new TestUser("test");
            var httpContext     = new Mock <HttpContext>();
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var claimsManager = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            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 <TestUser> >(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 <TestUser>(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);
        }
        public async Task CreateIdentityNullChecks()
        {
            var userManager = MockHelpers.MockUserManager <TestUser>().Object;
            var roleManager = MockHelpers.MockRoleManager <TestRole>().Object;
            var options     = new Mock <IOptions <IdentityOptions> >();

            Assert.Throws <ArgumentNullException>("optionsAccessor",
                                                  () => new UserClaimsPrincipalFactory <TestUser, TestRole>(userManager, roleManager, options.Object));
            var identityOptions = new IdentityOptions();

            options.Setup(a => a.Value).Returns(identityOptions);
            var factory = new UserClaimsPrincipalFactory <TestUser, TestRole>(userManager, roleManager, options.Object);
            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await factory.CreateAsync(null));
        }
Пример #6
0
        public async Task PasswordSignInFailsWithUnknownUser()
        {
            // Setup
            var manager = MockHelpers.MockUserManager <TestUser>();

            manager.Setup(m => m.FindByNameAsync("bogus")).ReturnsAsync(default(TestUser)).Verifiable();
            var context = new Mock <HttpContext>();
            var helper  = SetupSignInManager(manager.Object, context.Object);

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

            // Assert
            Assert.False(result.Succeeded);
            manager.Verify();
            context.Verify();
        }
Пример #7
0
        public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
        {
            var user            = new TestUser("test");
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            var identityOptions = new IdentityOptions {
                SecurityStampValidationInterval = TimeSpan.Zero
            };
            var options = new Mock <IOptions <IdentityOptions> >();

            options.Setup(a => a.Value).Returns(identityOptions);
            var httpContext     = new Mock <HttpContext>();
            var contextAccessor = new Mock <IHttpContextAccessor>();

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

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(null).Verifiable();
            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(signInManager.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(options.Object, signInManager.Object));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(identityOptions.Cookies.ApplicationCookieAuthenticationScheme);

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

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id),
                                                  new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow
            },
                                                  identityOptions.Cookies.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());

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

            Assert.Null(context.Principal);
            signInManager.VerifyAll();
        }
        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();
        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();
        }
        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();
        public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims)
        {
            // Setup
            var userManager = MockHelpers.MockUserManager <TestUser>();
            var roleManager = MockHelpers.MockRoleManager <TestRole>();
            var user        = new TestUser {
                UserName = "******"
            };

            userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims);
            userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles);
            userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id);
            userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName);
            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 TestRole()
            {
                Name = "Admin"
            };
            var local = new TestRole()
            {
                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 <TestUser, TestRole>(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(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();
        }