Example #1
0
        public async Task CanTwoFactorSignIn(bool isPersistent, bool supportsLockout, bool externalLogin, bool rememberClient)
        {
            // Setup
            var user = new TestUser {
                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 <TestUser> .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();
        }
Example #2
0
        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.Equal(1, principal.Identities.Count());
            Assert.Equal(identityOptions.Cookies.ApplicationCookieAuthenticationScheme, identity.AuthenticationType);
            var claims = identity.Claims.ToList();

            Assert.NotNull(claims);
            Assert.True(
                claims.Any(c => c.Type == manager.Options.ClaimsIdentity.UserNameClaimType && c.Value == user.UserName));
            Assert.True(claims.Any(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();
        }