예제 #1
0
 private static RoleManager <TestRole> CreateRoleManager(IRoleStore <TestRole> roleStore)
 {
     return(MockHelpers.TestRoleManager(roleStore));
 }
        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();
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser {
                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 <TestRole>();

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

            options.Setup(a => a.Value).Returns(new IdentityOptions());

            var securityStampOptions = new Mock <IOptions <SecurityStampValidatorOptions> >();

            securityStampOptions.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.Zero
            });

            var claimsFactory = new UserClaimsPrincipalFactory <TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);

            var loggerFactory = new MockLoggerFactory();
            var logger        = loggerFactory.CreateLogger <SignInManager <TestUser> >();

            var helper     = new Mock <SignInManager <TestUser> >(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger, new Mock <IAuthenticationSchemeProvider>().Object, new Mock <IUserConfirmation <TestUser> >().Object);
            var properties = new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow.AddSeconds(-1), IsPersistent = isPersistent
            };

            var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
            var principal = new ClaimsPrincipal(id);

            helper.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(user).Verifiable();
            helper.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable();

            var logFactory = new MockLoggerFactory();
            var services   = new ServiceCollection();

            services.AddSingleton <ILoggerFactory>(loggerFactory);
            services.AddSingleton(options.Object);
            services.AddSingleton(helper.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(securityStampOptions.Object, helper.Object, new SystemClock(), loggerFactory));

            context.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);

            var ticket = new AuthenticationTicket(principal,
                                                  properties,
                                                  IdentityConstants.ApplicationScheme);
            var cookieContext = new CookieValidatePrincipalContext(context.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
            {
                HandlerType = typeof(NoopHandler)
            }.Build(), new CookieAuthenticationOptions(), ticket);

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

            Assert.NotNull(cookieContext.Principal);
            helper.VerifyAll();
        }