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.Options).Returns(identityOptions);
     var factory = new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager, roleManager, options.Object);
     await Assert.ThrowsAsync<ArgumentNullException>("user",
         async () => await factory.CreateAsync(null));
 }
Beispiel #2
0
 public SignInManager(
     UserManager userManager,
     IHttpContextAccessor contextAccessor,
     UserClaimsPrincipalFactory claimsFactory,
     IOptions <IdentityOptions> optionsAccessor,
     ILogger <SignInManager <User> > logger,
     IUnitOfWorkManager unitOfWorkManager,
     ISettingManager settingManager,
     IAuthenticationSchemeProvider schemes
     ) : base(
         userManager,
         contextAccessor,
         claimsFactory,
         optionsAccessor,
         logger,
         unitOfWorkManager,
         settingManager,
         schemes)
 {
 }
Beispiel #3
0
 public PaymentController(
     IPaymentAppService paymentAppService,
     ITenantRegistrationAppService tenantRegistrationAppService,
     TenantManager tenantManager,
     EditionManager editionManager,
     IWebUrlService webUrlService,
     ISubscriptionPaymentRepository subscriptionPaymentRepository,
     UserClaimsPrincipalFactory <User, Role> userClaimsPrincipalFactory,
     UserManager userManager,
     SignInManager signInManager)
 {
     _paymentAppService            = paymentAppService;
     _tenantRegistrationAppService = tenantRegistrationAppService;
     _tenantManager  = tenantManager;
     _editionManager = editionManager;
     _webUrlService  = webUrlService;
     _subscriptionPaymentRepository = subscriptionPaymentRepository;
     _userClaimsPrincipalFactory    = userClaimsPrincipalFactory;
     _userManager   = userManager;
     _signInManager = signInManager;
 }
        public async Task PasswordSignInReturnsLockedOutWhenLockedOut()
        {
            // Setup
            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 identityOptions = new IdentityOptions();
            var options         = new Mock <IOptions <IdentityOptions> >();

            options.Setup(a => a.Options).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory <TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            var logStore      = new StringBuilder();
            var logger        = MockHelpers.MockILogger <SignInManager <TestUser> >(logStore);
            var helper        = new SignInManager <TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, null);

            helper.Logger = logger.Object;
            var expectedScope = string.Format("{0} for {1}: {2}", "PasswordSignInAsync", "user", user.Id);
            var expectedLog   = string.Format("{0} : {1}", "PasswordSignInAsync", "Lockedout");

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

            // Assert
            Assert.False(result.Succeeded);
            Assert.True(result.IsLockedOut);
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedLog));
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedScope));
            manager.Verify();
        }
Beispiel #5
0
        /// <summary>
        /// 客户端授权时的验证,授权类型为client_credentials
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var userService = context.HttpContext.ApplicationServices.GetService <UserService>();
            var roleService = context.HttpContext.ApplicationServices.GetService <RoleService>();
            var optionsMgr  = context.HttpContext.ApplicationServices.GetService <IOptions <IdentityOptions> >();

            User user = await userService.FindByUserToken(context.ClientId);

            if (user == null)
            {
                context.SetError("invalid_grant", Resources.Error_NotFounUserName);
                return;
            }

            UserClaimsPrincipalFactory <User, Role> claimsFactory
                = new UserClaimsPrincipalFactory <User, Role>(userService, roleService, optionsMgr);
            var principal = await claimsFactory.CreateAsync(user);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(principal, properties, OAuthDefaults.AuthenticationType);

            context.Validated(ticket);
        }
Beispiel #6
0
        private static SignInManager <TUser> BuildSignInManager <TUser>(UserManager <TUser> manager,
                                                                        HttpContext context, ILogger logger          = null, IdentityOptions identityOptions = null,
                                                                        IAuthenticationSchemeProvider schemeProvider = null) where TUser : class
        {
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(context);
            identityOptions = identityOptions ?? new IdentityOptions();

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

            options.Setup(a => a.Value).Returns(identityOptions);

            var claimsFactory = new UserClaimsPrincipalFactory <TUser>(manager, options.Object);

            schemeProvider = schemeProvider ?? new Mock <IAuthenticationSchemeProvider>().Object;

            var sm = new SignInManager <TUser>(manager, contextAccessor.Object, claimsFactory, options.Object, null, schemeProvider, new DefaultUserConfirmation <TUser>());

            sm.Logger = logger ?? (new Mock <ILogger <SignInManager <TUser> > >()).Object;

            return(sm);
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            using var scope = _scopeFactory.CreateScope();
            var userManager = scope.ServiceProvider.GetService <UserManager <TUser> >();
            var state       = base.GetAuthenticationStateAsync().Result;
            var user        = await userManager !.GetUserAsync(state.User);

            AuthenticationState result = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));

            if (user != null)
            {
                var roles            = await userManager !.GetRolesAsync(user);
                var principalFactory = new UserClaimsPrincipalFactory <TUser>(userManager, new OptionsWrapper <IdentityOptions>(_options));
                var principal        = await principalFactory.CreateAsync(user);

                var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(principal.Identity, roles.Select(role => new Claim(ClaimTypes.Role, role))));

                result = new AuthenticationState(claimsPrincipal);
            }

            NotifyAuthenticationStateChanged(Task.FromResult(result));

            return(result);
        }
        public async Task RememberClientStoresUserId()
        {
            // Setup
            var user = new TestUser { UserName = "******" };
            var manager = SetupUserManager(user);
            var context = new Mock<HttpContext>();
            var response = new Mock<HttpResponse>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            var roleManager = MockHelpers.MockRoleManager<TestRole>();
            var identityOptions = new IdentityOptions();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);

            context.Setup(c => c.Response).Returns(response.Object).Verifiable();
            response.Setup(r => r.SignIn(
                IdentityOptions.TwoFactorRememberMeCookieAuthenticationScheme,
                It.Is<ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id
                    && i.Identities.First().AuthenticationType == IdentityOptions.TwoFactorRememberMeCookieAuthenticationType),
                It.Is<AuthenticationProperties>(v => v.IsPersistent == true))).Verifiable();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object).Verifiable();
            options.Setup(a => a.Options).Returns(identityOptions).Verifiable();

            var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object);

            // Act
            await helper.RememberTwoFactorClientAsync(user);

            // Assert
            manager.Verify();
            context.Verify();
            response.Verify();
            contextAccessor.Verify();
            options.Verify();
        }
        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 Mock<HttpContext>();
            var response = new Mock<HttpResponse>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            var twoFactorInfo = new SignInManager<TestUser>.TwoFactorAuthenticationInfo { UserId = user.Id };
            var loginProvider = "loginprovider";
            var id = SignInManager<TestUser>.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null);
            var authResult = new AuthenticationResult(id, new AuthenticationProperties(), new AuthenticationDescription());
            var roleManager = MockHelpers.MockRoleManager<TestRole>();
            var identityOptions = new IdentityOptions();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            if (externalLogin)
            {
                response.Setup(r => r.SignIn(
                    IdentityOptions.ApplicationCookieAuthenticationScheme,
                    It.Is<ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.AuthenticationMethod) == loginProvider
                        && i.FindFirstValue(ClaimTypes.NameIdentifier) == user.Id),
                    It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Verifiable();
                response.Setup(r => r.SignOut(IdentityOptions.ExternalCookieAuthenticationScheme)).Verifiable();
            }
            else
            {
                SetupSignIn(response, user.Id);
            }
            if (rememberClient)
            {
                response.Setup(r => r.SignIn(
                    IdentityOptions.TwoFactorRememberMeCookieAuthenticationScheme,
                    It.Is<ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id
                        && i.Identities.First().AuthenticationType == IdentityOptions.TwoFactorRememberMeCookieAuthenticationType),
                    It.Is<AuthenticationProperties>(v => v.IsPersistent == true))).Verifiable();
            }
            context.Setup(c => c.Response).Returns(response.Object).Verifiable();
            context.Setup(c => c.AuthenticateAsync(IdentityOptions.TwoFactorUserIdCookieAuthenticationScheme)).ReturnsAsync(authResult).Verifiable();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var logStore = new StringBuilder();
            var logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore);
            var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, null);
            helper.Logger = logger.Object;
            string expectedScope = string.Format("{0} for {1}: {2}", "TwoFactorSignInAsync", "user", user.Id);
            string expectedLog = string.Format("{0} : {1}", "TwoFactorSignInAsync", "Succeeded");

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

            // Assert
            Assert.True(result.Succeeded);
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedLog));
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedScope));
            manager.Verify();
            context.Verify();
            response.Verify();
            contextAccessor.Verify();
        }
Beispiel #10
0
        public async Task CanExternalSignIn(bool isPersistent, bool supportsLockout)
        {
            // Setup
            var user = new TestUser { 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 Mock<HttpContext>();
            var response = new Mock<HttpResponse>();
            context.Setup(c => c.Response).Returns(response.Object).Verifiable();
            SetupSignIn(response, user.Id, isPersistent, loginProvider);
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var roleManager = MockHelpers.MockRoleManager<TestRole>();
            var identityOptions = new IdentityOptions();
            response.Setup(r => r.SignOut(IdentityOptions.ExternalCookieAuthenticationScheme)).Verifiable();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            var logStore = new StringBuilder();
            var logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore);
            var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, null);
            helper.Logger = logger.Object;
            string expectedScope = string.Format("{0} for {1}: {2}", "ExternalLoginSignInAsync", "user", user.Id);
            string expectedLog = string.Format("{0} : {1}", "ExternalLoginSignInAsync", "Succeeded");

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

            // Assert
            Assert.True(result.Succeeded);
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedLog));
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedScope));
            manager.Verify();
            context.Verify();
            response.Verify();
            contextAccessor.Verify();
        }
Beispiel #11
0
        public async Task PasswordSignInWorksWithNonTwoFactorStore()
        {
            // Setup
            var user = new TestUser { 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 Mock<HttpContext>();
            var response = new Mock<HttpResponse>();
            SetupSignIn(response);
            context.Setup(c => c.Response).Returns(response.Object).Verifiable();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var roleManager = MockHelpers.MockRoleManager<TestRole>();
            var identityOptions = new IdentityOptions();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object);

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

            // Assert
            Assert.True(result.Succeeded);
            manager.Verify();
            context.Verify();
            response.Verify();
            contextAccessor.Verify();
        }
Beispiel #12
0
        public async Task CanPasswordSignIn(bool isPersistent)
        {
            // Setup
            var user = new TestUser { 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 Mock<HttpContext>();
            var response = new Mock<HttpResponse>();
            context.Setup(c => c.Response).Returns(response.Object).Verifiable();
            SetupSignIn(response, user.Id, isPersistent);
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
            var roleManager = MockHelpers.MockRoleManager<TestRole>();
            var identityOptions = new IdentityOptions();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            var logStore = new StringBuilder();
            var logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore);
            var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, null);
            helper.Logger = logger.Object;
            string expectedScope = string.Format("{0} for {1}: {2}", "PasswordSignInAsync", "user", user.Id);
            string expectedLog = string.Format("{0} : {1}", "PasswordSignInAsync", "Succeeded");

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

            // Assert
            Assert.True(result.Succeeded);
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedLog));
            Assert.NotEqual(-1, logStore.ToString().IndexOf(expectedScope));
            manager.Verify();
            context.Verify();
            response.Verify();
            contextAccessor.Verify();
        }
        public async Task <ActionResult> CreateAdmin(AdminViewModel viewModel)
        {
            if (viewModel.AdminPassword != viewModel.ConfirmPassword)
            {
                ViewBag.Languages = new SelectList(SupportedCultures.Cultures.Select(x => new { Value = x.TwoLetterISOLanguageName, Text = x.DisplayName }).ToList(), "Value", "Text");
                ModelState.AddModelError("ConfirmPassword", "Password does not match");
                return(View(viewModel));
            }

            SetupHelper.InitilizeDatabase();

            if (SetupHelper.IsDbCreateComplete == true && SetupHelper.IsAdminCreateComplete == false)
            {
                if (!ModelState.IsValid)
                {
                    ViewBag.Languages = new SelectList(SupportedCultures.Cultures.Select(x => new { Value = x.TwoLetterISOLanguageName, Text = x.DisplayName }).ToList(), "Value", "Text");
                    return(View(viewModel));
                }

                var optionBuilder = new DbContextOptionsBuilder <NccDbContext>();

                SupportedDatabases supportedDatabases = TypeConverter.TryParseDatabaseEnum(SetupHelper.SelectedDatabase);

                switch (supportedDatabases)
                {
                case SupportedDatabases.MSSQL:
                    optionBuilder.UseSqlServer(SetupHelper.ConnectionString, opts => opts.MigrationsAssembly("NetCoreCMS.Framework"));
                    break;

                case SupportedDatabases.MsSqlLocalStorage:
                    break;

                case SupportedDatabases.MySql:
                    optionBuilder.UseMySql(SetupHelper.ConnectionString, opts => opts.MigrationsAssembly("NetCoreCMS.Framework"));
                    break;

                case SupportedDatabases.SqLite:
                    optionBuilder.UseSqlite(SetupHelper.ConnectionString, opts => opts.MigrationsAssembly("NetCoreCMS.Framework"));
                    break;

                case SupportedDatabases.PgSql:
                    break;
                }

                var nccDbConetxt = new NccDbContext(optionBuilder.Options);

                var userStore              = new NccUserStore(nccDbConetxt);
                var identityOptions        = Options.Create(new IdentityOptions());
                var passwordHasher         = new PasswordHasher <NccUser>();
                var userValidatorList      = new List <UserValidator <NccUser> >();
                var passwordValidatorList  = new List <PasswordValidator <NccUser> >();
                var lookupNormalizer       = new UpperInvariantLookupNormalizer();
                var identityErrorDescriber = new IdentityErrorDescriber();
                var logger     = _loggerFactory.CreateLogger <UserManager <NccUser> >();
                var authOption = new AuthenticationOptions();
                var options    = Options.Create <AuthenticationOptions>(authOption);
                var scheme     = new AuthenticationSchemeProvider(options);

                var userManager = new UserManager <NccUser>(
                    userStore,
                    identityOptions,
                    passwordHasher,
                    userValidatorList,
                    passwordValidatorList,
                    lookupNormalizer,
                    identityErrorDescriber,
                    GlobalContext.App.ApplicationServices,
                    logger
                    );

                var roleStore         = new NccRoleStore(nccDbConetxt);
                var roleValidatorList = new List <RoleValidator <NccRole> >();
                var roleLogger        = _loggerFactory.CreateLogger <RoleManager <NccRole> >();

                var roleManager = new RoleManager <NccRole>(
                    roleStore,
                    roleValidatorList,
                    new UpperInvariantLookupNormalizer(),
                    new IdentityErrorDescriber(),
                    roleLogger
                    );

                var claimsFactory = new UserClaimsPrincipalFactory <NccUser, NccRole>(userManager, roleManager, identityOptions);
                var signInLogger  = _loggerFactory.CreateLogger <SignInManager <NccUser> >();
                var signInManager = new NccSignInManager <NccUser>(userManager, _httpContextAccessor, claimsFactory, identityOptions, signInLogger, scheme);

                //nccDbConetxt.Database.Migrate();

                var setupInfo = new WebSiteInfo()
                {
                    SiteName         = viewModel.SiteName,
                    Tagline          = viewModel.Tagline,
                    AdminPassword    = viewModel.AdminPassword,
                    AdminUserName    = viewModel.AdminUserName,
                    ConnectionString = SetupHelper.ConnectionString,
                    Database         = TypeConverter.TryParseDatabaseEnum(SetupHelper.SelectedDatabase),
                    Email            = viewModel.Email,
                    Language         = viewModel.Language,
                    TablePrefix      = viewModel.TablePrefix
                };

                //SetupHelper.RegisterAuthServices(supportedDatabases);
                var admin = await SetupHelper.CreateSuperAdminUser(nccDbConetxt, userManager, roleManager, signInManager, setupInfo);

                if (admin != null)
                {
                    SetupHelper.IsAdminCreateComplete = true;
                    SetupHelper.Language = viewModel.Language;
                    SetupHelper.SaveSetup();
                    SetupHelper.CrateNccWebSite(nccDbConetxt, setupInfo);

                    await SetupHelper.SaveBasicData(admin, nccDbConetxt, userManager, roleManager, signInManager, setupInfo);

                    return(Redirect("/Home/SetupSuccess"));
                }
                else
                {
                    TempData["ErrorMessage"] = "Could not create Admin user and Roles.";
                    return(Redirect("/Home/Error"));
                }
            }

            TempData["ErrorMessage"] = "Setup already completed.";
            return(Redirect("/Home/Error"));
        }
        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()));

            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();
        }
Beispiel #15
0
 public KanekoProfileService(AspNetAccountDbContext context,
                             UserClaimsPrincipalFactory <ApplicationUser> userClaimsPrincipalFactory)
 {
     _context = context;
     _userClaimsPrincipalFactory = userClaimsPrincipalFactory;
 }
Beispiel #16
0
        /// <summary>
        /// Create and init the context.
        /// </summary>
        /// <param name="dbctx"></param>
        /// <param name="host"></param>
        /// <param name="path"></param>
        /// <param name="regionName"></param>
        /// <param name="user"></param>
        /// <param name="checkInitResults"></param>
        /// <returns></returns>
        protected async Task <WcmsAppContext> CreateAndInitAppContext(AppDbContext dbctx, string host, string path, string regionName, ApplicationUser user = null, bool checkInitResults = true)
        {
            // Check the service provider...
            Assert.NotEqual(null, _serviceProvider);

            // Create and init the http context...
            var httpContext = new DefaultHttpContext();

            Assert.NotEqual(null, httpContext);
            // Configure the http context...
            httpContext.RequestServices = _services.BuildServiceProvider();
            Assert.NotEqual(null, httpContext.RequestServices);
            httpContext.Request.Host = new HostString(host);
            httpContext.Request.Path = new PathString(path);
            // Add user to the http context...
            if (user != null)
            {
                UserClaimsPrincipalFactory <ApplicationUser, IdentityRole> clmFact
                    = _GetRequiredServicee <UserClaimsPrincipalFactory <ApplicationUser, IdentityRole> >(httpContext.RequestServices);
                Assert.NotEqual(null, clmFact);
                httpContext.User = /*ClaimsPrincipal upp =*/ await clmFact.CreateAsync(user);

                Assert.NotEqual(null, httpContext.User /*upp*/);
                //httpContext.User = new ClaimsPrincipal(upp);
            }

            // Create and init the route context...
            var routeContext = new RouteContext(httpContext);

            Assert.NotEqual(null, routeContext);
            // Configure the route context...
            routeContext.RouteData = new RouteData();
            Assert.NotEqual(null, routeContext.RouteData);
            routeContext.RouteData.Values.Add(CRoute.RegionTagName, regionName);

            // Build loger factory...
            var logFactory =
                _GetRequiredServicee <ILoggerFactory>(httpContext.RequestServices);

            Assert.NotEqual(null, logFactory);
#if DEBUG
            //logFactory.AddConsole(_LogFilter);
            logFactory.AddDebug(_LogFilter);
#endif

            // Create and init the context...
            WcmsAppContext ctx =
                _GetRequiredServicee <WcmsAppContext>(httpContext.RequestServices);
            Assert.NotEqual(null, ctx);
            Assert.Equal(null, ctx.User);
            Assert.Equal(null, ctx.Site);
            //ctx.UnitTestInit(dbctx);
            int initSiteAsyncRes = await ctx.InitSiteAsync(httpContext,
                                                           _GetRequiredServicee <IAuthorizationService>(httpContext.RequestServices));

            bool initRouteAsyncRes = await ctx.InitRouteAsync(routeContext);

            if (checkInitResults == true)
            {
                Assert.Equal(3, initSiteAsyncRes); // No module registered.
                Assert.Equal(true, initRouteAsyncRes);
            }
            return(ctx);
        }
        private Mock<SignInManager<AccountingUser>> BuildMockSignInManager(bool signIn = true)
        {
            var userManager = BuildMockUserRepo();

            var context = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);

            var roleStore = new Mock<IRoleStore<string>>().Object;
            var roles = new List<IRoleValidator<string>>();
            var roleManager = new RoleManager<string>(roleStore, roles,
                new UpperInvariantLookupNormalizer(),
                new IdentityErrorDescriber(),
                null,
                null);

            var identityOptions = new IdentityOptions();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Value).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<AccountingUser, string>(userManager.Object, roleManager, options.Object);

            var manager = new Mock<SignInManager<AccountingUser>>(userManager.Object, contextAccessor.Object, claimsFactory, null, null);

            manager.Setup(mgr => mgr.PasswordSignInAsync(It.IsAny<AccountingUser>(), It.IsAny<string>(), true, false))
                .Returns(Task.FromResult(signIn ? SignInResult.Success : SignInResult.Failed));

            manager.Setup(mgr => mgr.SignOutAsync())
                .Returns(Task.FromResult(0));

            return manager;
        }
Beispiel #18
0
        public IdentityServiceFactory()
        {
            var dataProtectorTokenProvider = new DataProtectorTokenProvider <DbUser>(
                new EphemeralDataProtectionProvider(new NullLoggerFactory()), null, new NullLogger <DataProtectorTokenProvider <DbUser> >());

            // service provider
            var serviceProviderMock = new Mock <IServiceProvider>();

            var serviceScopeMock = new Mock <IServiceScope>();

            serviceScopeMock.Setup(x => x.ServiceProvider).Returns(serviceProviderMock.Object);

            var serviceScopeFactoryMock = new Mock <IServiceScopeFactory>();

            serviceScopeFactoryMock.Setup(x => x.CreateScope()).Returns(serviceScopeMock.Object);

            var authenticationServiceMock = new Mock <IAuthenticationService>();

            serviceProviderMock.Setup(x => x.GetService(typeof(IServiceScopeFactory))).Returns(serviceScopeFactoryMock.Object);
            serviceProviderMock.Setup(x => x.GetService(typeof(DataProtectorTokenProvider <DbUser>))).Returns(dataProtectorTokenProvider);
            serviceProviderMock.Setup(x => x.GetService(typeof(IAuthenticationService))).Returns(authenticationServiceMock.Object);

            // http context
            var httpContextAccessorMock = new Mock <IHttpContextAccessor>();
            var httpContext             = new DefaultHttpContext {
                ServiceScopeFactory = serviceScopeFactoryMock.Object
            };

            httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext);
            var httpContextAccessor = httpContextAccessorMock.Object;

            // identity services
            var identityOptionsAccessorMock = new Mock <IOptions <IdentityOptions> >();

            identityOptionsAccessorMock.Setup(x => x.Value).Returns(() => new IdentityOptions
            {
                Tokens = new TokenOptions
                {
                    ProviderMap = new Dictionary <string, TokenProviderDescriptor>
                    {
                        { TokenOptions.DefaultProvider, new TokenProviderDescriptor(typeof(DataProtectorTokenProvider <DbUser>)) },
                        // { TokenOptions.DefaultEmailProvider, new TokenProviderDescriptor(typeof(EmailTokenProvider<DbUser>)) }
                    }
                },
                User = new UserOptions
                {
                    RequireUniqueEmail = true
                }
            });
            var identityOptionsAccessor = identityOptionsAccessorMock.Object;

            var identityErrorDescriber = new IdentityErrorDescriber();
            var lookupNormalizer       = new UpperInvariantLookupNormalizer();

            var connectionFactory = new DbConnectionFactory();

            var userStore = new UserStore <Guid, DbUser, DbRole>(connectionFactory, identityErrorDescriber);
            var roleStore = new RoleStore <Guid, DbRole>(connectionFactory, identityErrorDescriber);

            var userManager = new UserManager <DbUser>(userStore, identityOptionsAccessor, new PasswordHasher <DbUser>(), null, null,
                                                       lookupNormalizer, identityErrorDescriber, serviceProviderMock.Object, new NullLogger <UserManager <DbUser> >());

            userManager.RegisterTokenProvider(TokenOptions.DefaultProvider, dataProtectorTokenProvider);

            var roleManager = new AspNetRoleManager <DbRole>(roleStore, null, lookupNormalizer, identityErrorDescriber,
                                                             new NullLogger <RoleManager <DbRole> >(), httpContextAccessor);
            var userClaimsPrincipalFactory = new UserClaimsPrincipalFactory <DbUser, DbRole>(userManager, roleManager, identityOptionsAccessor);
            var signInManager = new SignInManager <DbUser>(userManager, httpContextAccessor, userClaimsPrincipalFactory, identityOptionsAccessor,
                                                           new NullLogger <SignInManager <DbUser> >(), null, null);

            UserManager   = userManager;
            RoleManager   = roleManager;
            SignInManager = signInManager;
        }
        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.Options).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.ApplicationCookieAuthenticationType, 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();
        }
Beispiel #20
0
        public async Task PasswordSignInReturnsLockedOutWhenLockedOut()
        {
            // Setup
            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 identityOptions = new IdentityOptions();
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Value).Returns(identityOptions);
            var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            var logStore = new StringBuilder();
            var logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore);
            var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger.Object);

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

            // Assert
            Assert.False(result.Succeeded);
            Assert.True(result.IsLockedOut);
            Assert.True(logStore.ToString().Contains($"User {user.Id} is currently locked out."));
            manager.Verify();
        }
Beispiel #21
0
 private static SignInManager<TestUser> SetupSignInManager(UserManager<TestUser> manager, HttpContext context, StringBuilder logStore = null, IdentityOptions identityOptions = null)
 {
     var contextAccessor = new Mock<IHttpContextAccessor>();
     contextAccessor.Setup(a => a.HttpContext).Returns(context);
     var roleManager = MockHelpers.MockRoleManager<TestRole>();
     identityOptions = identityOptions ?? new IdentityOptions();
     var options = new Mock<IOptions<IdentityOptions>>();
     options.Setup(a => a.Value).Returns(identityOptions);
     var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager, roleManager.Object, options.Object);
     var sm = new SignInManager<TestUser>(manager, contextAccessor.Object, claimsFactory, options.Object, null);
     sm.Logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore ?? new StringBuilder()).Object;
     return sm;
 }
Beispiel #22
0
 public CustomerLogInManager(CustomerManager userManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IRepository <CustomerLoginAttempt, long> userLoginAttemptRepository, IIocResolver iocResolver, IPasswordHasher <Customer> passwordHasher, UserClaimsPrincipalFactory <Customer> claimsPrincipalFactory) : base(userManager, unitOfWorkManager, settingManager, userLoginAttemptRepository, iocResolver, passwordHasher, claimsPrincipalFactory)
 {
 }
Beispiel #23
0
 public ClaimFactory(UserClaimsPrincipalFactory <User> defaultFactory, ProjectDbContext dbContext)
 {
     this.defaultFactory = defaultFactory;
     this.dbContext      = dbContext;
 }
        public async Task <ActionResult> CreateAdmin(AdminViewModel viewModel)
        {
            SetupHelper.InitilizeDatabase();

            var optionBuilder = new DbContextOptionsBuilder <NccDbContext>();

            DatabaseEngine dbe = TypeConverter.TryParseDatabaseEnum(SetupHelper.SelectedDatabase);

            switch (dbe)
            {
            case DatabaseEngine.MSSQL:
                optionBuilder.UseSqlServer(SetupHelper.ConnectionString, opts => opts.MigrationsAssembly("NetCoreCMS.Framework"));
                break;

            case DatabaseEngine.MsSqlLocalStorage:
                break;

            case DatabaseEngine.MySql:
                optionBuilder.UseMySql(SetupHelper.ConnectionString, opts => opts.MigrationsAssembly("NetCoreCMS.Framework"));
                break;

            case DatabaseEngine.SqLite:
                optionBuilder.UseSqlite(SetupHelper.ConnectionString, opts => opts.MigrationsAssembly("NetCoreCMS.Framework"));
                break;

            case DatabaseEngine.PgSql:
                break;
            }

            var nccDbConetxt = new NccDbContext(optionBuilder.Options);

            var userStore              = new NccUserStore(nccDbConetxt);
            var identityOptions        = Options.Create(new IdentityOptions());
            var passwordHasher         = new PasswordHasher <NccUser>();
            var userValidatorList      = new List <UserValidator <NccUser> >();
            var passwordValidatorList  = new List <PasswordValidator <NccUser> >();
            var lookupNormalizer       = new UpperInvariantLookupNormalizer();
            var identityErrorDescriber = new IdentityErrorDescriber();
            var logger = _loggerFactory.CreateLogger <UserManager <NccUser> >();

            var userManager = new UserManager <NccUser>(
                userStore,
                identityOptions,
                passwordHasher,
                userValidatorList,
                passwordValidatorList,
                lookupNormalizer,
                identityErrorDescriber,
                GlobalConfig.App.ApplicationServices,
                logger
                );

            var roleStore         = new NccRoleStore(nccDbConetxt);
            var roleValidatorList = new List <RoleValidator <NccRole> >();
            var roleLogger        = _loggerFactory.CreateLogger <RoleManager <NccRole> >();

            var roleManager = new RoleManager <NccRole>(
                roleStore,
                roleValidatorList,
                new UpperInvariantLookupNormalizer(),
                new IdentityErrorDescriber(),
                roleLogger,
                _httpContextAccessor
                );

            var claimsFactory = new UserClaimsPrincipalFactory <NccUser, NccRole>(userManager, roleManager, identityOptions);
            var signInLogger  = _loggerFactory.CreateLogger <SignInManager <NccUser> >();
            var signInManager = new NccSignInManager <NccUser>(userManager, _httpContextAccessor, claimsFactory, identityOptions, signInLogger);

            //nccDbConetxt.Database.Migrate();

            var setupInfo = new WebSiteInfo()
            {
                SiteName         = viewModel.SiteName,
                Tagline          = viewModel.Tagline,
                AdminPassword    = viewModel.AdminPassword,
                AdminUserName    = viewModel.AdminUserName,
                ConnectionString = SetupHelper.ConnectionString,
                Database         = TypeConverter.TryParseDatabaseEnum(SetupHelper.SelectedDatabase),
                Email            = viewModel.Email
            };

            var admin = await SetupHelper.CreateSuperAdminUser(userManager, roleManager, signInManager, setupInfo);

            SetupHelper.RegisterAuthServices();
            SetupHelper.IsAdminCreateComplete = true;
            SetupHelper.SaveSetup();
            SetupHelper.CrateNccWebSite(nccDbConetxt, setupInfo);

            return(Redirect("/Home/SetupSuccess"));
        }
    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();
    }
Beispiel #26
0
 public AuthenticationService(IUserClaimsPrincipalFactory <TUser> claimsPrincipalFactory, UserManager <TUser> userManager, SignInManager <TUser> signInManager)
 {
     _claimsPrincipalFactory = claimsPrincipalFactory as UserClaimsPrincipalFactory <TUser, TRole>;
     _userManager            = userManager;
     _signInManager          = signInManager;
 }