Пример #1
0
        public async Task CreateUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user.
            var user = new TestUser { UserName = "******" };
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                transaction.Commit();
            }
            // Check the user has an id.
            Assert.IsNotNull(user.Id);

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(user.Id);
                transaction.Commit();
            }
            // Check we have the same user.
            Assert.AreEqual(user.Id, loadUser.Id);
            Assert.AreEqual(user.UserName, loadUser.UserName);
        }
Пример #2
0
        protected void InternalSetup()
        {
            HttpContext.Current = CreateHttpContext(userLoggedIn: false);
            var testStore = new TestUserStore();

            CurrentUserManagerMock = new Mock<ApplicationUserManager>(testStore);
            CurrentUserManagerMock.Setup(x => x.FindByEmailAsync(It.IsAny<string>()))
                .Returns(Task.FromResult(testStore.FindByIdAsync(UserId).Result));

            CurrentUserManagerMock.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>()))
                .Returns(Task.FromResult(IdentityResult.Success));

            CurrentUserManagerMock.Setup(u => u.RequestPhoneNumberConfirmationTokenAsync(It.IsAny<string>()))
                .Returns(Task.FromResult(0));

            CurrentUserManagerMock.Setup(u => u.ConfirmPhoneNumberAsync(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(Task.FromResult(IdentityResult.Failed(ApplicationMessages.InvalidVerificationCode)));

            CurrentUserManagerMock.Setup(u => u.ConfirmPhoneNumberAsync(UserId, VALID_CODE))
                .Returns(Task.FromResult(IdentityResult.Success))
                .Callback(() => testStore.FindByIdAsync(UserId).Result.PhoneNumberConfirmed = true);

            CurrentUserManagerMock.Setup(u => u.FindByIdAsync(UserId))
                .Returns(Task.FromResult(testStore.FindByIdAsync(UserId).Result));

            var authenticationManager = new Mock<IAuthenticationManager>();
            CurrentSignInManagerMock =
                new Mock<ApplicationSignInManager>(CurrentUserManagerMock.Object, authenticationManager.Object);
        }
        public virtual void Init()
        {
            store = new TestUserStore();
            manager = new TestIdentityRebootUserManager(store, 100);

            user = new TestUser()
            {
                UserName = username
            };
            var result = manager.Create(user, password);
            Assert.IsTrue(result.Succeeded);
        }
Пример #4
0
        public AccountController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IAuthenticationSchemeProvider schemeProvider,
            IEventService events,
            IPersistedGrantService persistedGrantService,
            TestUserStore users = null)
        {
            _users = users;

            _interaction           = interaction;
            _clientStore           = clientStore;
            _schemeProvider        = schemeProvider;
            _events                = events;
            _persistedGrantService = persistedGrantService;
        }
Пример #5
0
 public AccountController(
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IHttpContextAccessor httpContextAccessor,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     IAccountService accountService,
     IOptions <AccountOptions> options, TestUserStore users = null)
 {
     // if the TestUserStore is not in DI, then we'll just use the global users collection
     _users          = users ?? new TestUserStore(TestUsers.Users);
     _interaction    = interaction;
     _events         = events;
     _accountService = accountService;
     _options        = options;
 }
        public AccountController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IAuthenticationSchemeProvider schemeProvider,
            IEventService events,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _users = users ?? new TestUserStore(TestUsers.Users);

            _interaction    = interaction;
            _clientStore    = clientStore;
            _schemeProvider = schemeProvider;
            _events         = events;
        }
        public async Task GetNonExistingUserByNameReturnsNull()
        {
            // Create a session and user store for this test.
            var      session   = SessionFactory.OpenSession();
            var      userStore = new TestUserStore(session);
            TestUser user;

            using (var transaction = session.BeginTransaction())
            {
                user = await userStore.FindByNameAsync("THISISNOTAUSERNAME");

                transaction.Commit();
            }
            // Check that we have no user.
            Assert.IsNull(user);
        }
Пример #8
0
        public ExternalController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IEventService events,
            ILogger <ExternalController> logger,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _users = users;

            _interaction = interaction;
            _clientStore = clientStore;
            _logger      = logger;
            _events      = events;
        }
Пример #9
0
        protected void Init()
        {
            UserStore   = new TestUserStore <ApplicationUser>();
            UserManager = ApplicationUserManager.Create(UserStore);
            var user = new ApplicationUser()
            {
                Email    = TestConfig.TestUserEmail,
                Name     = "Test User",
                UserName = TestConfig.TestUserEmail
            };

            UserManager.CreateAsync(user, TestConfig.TestUserPassword).Wait();

            AuthMock      = GetAuthenticationManagerMock(false, false);
            SignInManager = new ApplicationSignInManager(UserManager, AuthMock.Object);
        }
 public ExternalLoginModel(
     SignInManager <ApplicationUser> signInManager,
     UserManager <ApplicationUser> userManager,
     ILogger <ExternalLoginModel> logger,
     IIdentityServerInteractionService interaction,
     IEventService events,
     TestUserStore users = null)
 {
     _signInManager = signInManager;
     _userManager   = userManager;
     _logger        = logger;
     // if the TestUserStore is not in DI, then we'll just use the global users collection
     // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
     _users       = users ?? new TestUserStore(TestUsers.Users);
     _interaction = interaction;
     _events      = events;
 }
Пример #11
0
 public AccountController(
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IHttpContextAccessor httpContextAccessor,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     ISqlContext _Sql, ISqlContext sqlContext,
     TestUserStore users = null)
 {
     // if the TestUserStore is not in DI, then we'll just use the global users collection
     _users       = users ?? new TestUserStore(TestUsers.Users);
     SqlContext   = sqlContext;
     _interaction = interaction;
     _events      = events;
     _account     = new AccountService(interaction, httpContextAccessor, schemeProvider, clientStore);
     Sql          = _Sql;
 }
        public async Task RemoveClaimForUser()
        {
            // Create a session and user store for this test.
            var session   = SessionFactory.OpenSession();
            var userStore = new TestUserStore(session);
            // Create and save a user with a claim.
            var user = new TestUser {
                UserName = "******"
            };
            var claimType  = ClaimTypes.Role;
            var claimValue = "Admin_RemoveClaimForUserTest";
            var claim      = new Claim(claimType, claimValue);

            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);

                await userStore.AddClaimsAsync(user, new[] { claim });

                transaction.Commit();
            }
            // Check the user has an id and the claim.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Claims.Count, 1);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session   = SessionFactory.OpenSession();
            userStore = new TestUserStore(session);
            // Load the user and remove the claim.
            TestUser loadUser;

            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);

                await userStore.RemoveClaimsAsync(loadUser, new[] { claim });

                transaction.Commit();
            }
            // Check we have the same user and it now has no claims.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(loadUser.Claims.Count, 0);
        }
Пример #13
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!InteractionService.IsValidReturnUrl(model.ReturnUrl))
            {
                throw new InvalidOperationException($"The url of '{model.ReturnUrl}' is not a valid return url.");
            }

            if (ModelState.IsValid)
            {
                if (TestUserStore.ValidateCredentials(model.Username, model.Password))
                {
                    var expiry = DateTimeOffset.UtcNow.Add(AuthorizationOptions.RefreshTokenLifetime);
                    var props  = model.RememberLogin ?
                                 new AuthenticationProperties {
                        ExpiresUtc = expiry, IsPersistent = true
                    } :
                    null;

                    var user = TestUserStore.FindByUsername(model.Username);
                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    return(Redirect(model.ReturnUrl));
                }

                ModelState.AddModelError(string.Empty, "Invalid username or password");
            }

            var authorizationContext = await InteractionService.GetAuthorizationContextAsync(model.ReturnUrl);

            var externalProviders = await GetProvidersAsync(authorizationContext);

            var viewModel = new LoginViewModel
            {
                Username          = model.Username,
                Password          = model.Password,
                RememberLogin     = model.RememberLogin,
                ReturnUrl         = model.ReturnUrl,
                ExternalProviders = externalProviders
            };

            return(View(nameof(Login), viewModel));
        }
Пример #14
0
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     TestUserStore users = null)
 {
     _users          = users ?? new TestUserStore(TestUsers.Users);
     _userManager    = userManager;
     _signInManager  = signInManager;
     _interaction    = interaction;
     _clientStore    = clientStore;
     _schemeProvider = schemeProvider;
     _events         = events;
 }
Пример #15
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl)
        {
            if (returnUrl == null)
            {
                throw new ArgumentNullException(nameof(returnUrl));
            }

            var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

            var tempUser = info?.Principal;

            if (tempUser == null)
            {
                throw new InvalidOperationException("External authentication error.");
            }

            var claims = tempUser.Claims.ToList();

            var subject        = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject);
            var nameIdentifier = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            var userIdClaim    = subject ?? nameIdentifier;

            if (userIdClaim == null)
            {
                throw new InvalidOperationException("unknown userid");
            }

            claims.Remove(userIdClaim);
            var provider = info.Properties.Items["scheme"];
            var userId   = userIdClaim.Value;

            var user = TestUserStore.FindByExternalProvider(provider, userId) ?? TestUserStore.AutoProvisionUser(provider, userId, claims);

            var sessionClaims = claims.Where(c => c.Type == JwtClaimTypes.SessionId).ToArray();

            var idToken = info.Properties.GetTokenValue("id_token");
            var props   = idToken != null ? new AuthenticationProperties(new Dictionary <string, string> {
                ["id_token"] = idToken
            }) : null;

            await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, provider, props, sessionClaims);

            await HttpContext.Authentication.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

            return(Redirect(returnUrl));
        }
Пример #16
0
    public Index(
        IIdentityServerInteractionService interaction,
        IClientStore clientStore,
        IAuthenticationSchemeProvider schemeProvider,
        IIdentityProviderStore identityProviderStore,
        IEventService events,
        TestUserStore users = null)
    {
        // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
        _users = users ?? throw new Exception("Please call 'AddTestUsers(TestUsers.Users)' on the IIdentityServerBuilder in Startup or remove the TestUserStore from the AccountController.");

        _interaction           = interaction;
        _clientStore           = clientStore;
        _schemeProvider        = schemeProvider;
        _identityProviderStore = identityProviderStore;
        _events = events;
    }
Пример #17
0
        public AccountController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IAuthenticationSchemeProvider schemeProvider,
            IEventService events,
            ILogger <AccountController> logger,
            TestUserStore users = null)

        {
            _users = users;

            _interaction    = interaction;
            _clientStore    = clientStore;
            _schemeProvider = schemeProvider;
            _events         = events;
            _logger         = logger;
        }
Пример #18
0
        public AccountController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IEventService events,
            IOptions <CMAdminConfiguration> cmAdminConfig,
            IOptions <IdentityServerUrlSettings> identityConfig,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _users = users ?? new TestUserStore(Config.GetSystemUsers(_cmAdminConfig.Value.Username, _cmAdminConfig.Value.Password));

            _interaction    = interaction;
            _clientStore    = clientStore;
            _events         = events;
            _cmAdminConfig  = cmAdminConfig;
            _identityConfig = identityConfig;
        }
        public AccountController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IAuthenticationSchemeProvider schemeProvider,
            IEventService events,
            IDataProtectionProvider provider,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _users = users ?? new TestUserStore(TestUsers.Users);

            _interaction    = interaction;
            _clientStore    = clientStore;
            _schemeProvider = schemeProvider;
            _events         = events;
            _protector      = provider.CreateProtector("ApiSecurityInDepth.IDP.DelegationDataBagCookie");
        }
Пример #20
0
 public AccountController(UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager,
                          IIdentityServerInteractionService interaction,
                          IClientStore clientStore,
                          IAuthenticationSchemeProvider schemeProvider,
                          IEventService events, ILogger <AccountController> logger, IUnitOfWork unitOfWork,
                          TestUserStore users = null)
 {
     // if the TestUserStore is not in DI, then we'll just use the global users collection
     // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
     _users          = users ?? new TestUserStore(TestUsers.Users);
     _logger         = logger;
     _signInManager  = signInManager;
     _userManager    = userManager;
     _interaction    = interaction;
     _clientStore    = clientStore;
     _schemeProvider = schemeProvider;
     _events         = events; _unitOfWork = unitOfWork;
 }
Пример #21
0
        public ExternalController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IEventService events,
            UserManager <ApplicationUser> userManager,
            SignInManager <ApplicationUser> signInManager,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _users         = users ?? new TestUserStore(TestUsers.Users);
            _userManager   = userManager;
            _signInManager = signInManager;

            _interaction = interaction;
            _clientStore = clientStore;
            _events      = events;
        }
Пример #22
0
        /// <summary>
        /// This method is called whenever claims about the user are requested (e.g. during token creation or via the userinfo endpoint)
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            context.LogProfileRequest(Logger);

            if (context.RequestedClaimTypes.Any())
            {
                var user = new TestUserStore(_security.CurrentValue.Users).FindBySubjectId(context.Subject.GetSubjectId());
                if (user != null)
                {
                    context.AddRequestedClaims(user.Claims);
                }
            }

            context.IssuedClaims = context.Subject.Claims.ToList();
            context.LogIssuedClaims(Logger);

            return(Task.CompletedTask);
        }
Пример #23
0
        public AccountController(
            ISamlInteractionService samlInteractionService,
            ISamlMessageParser samlMessageParser,
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IAuthenticationSchemeProvider schemeProvider,
            IEventService events,
            TestUserStore users = null)
        {
            this.samlInteractionService = samlInteractionService ?? throw new ArgumentNullException(nameof(samlInteractionService));
            this.samlMessageParser      = samlMessageParser ?? throw new ArgumentNullException(nameof(samlMessageParser));
            this.interaction            = interaction;
            this.clientStore            = clientStore;
            this.schemeProvider         = schemeProvider;
            this.events = events;

            this.users = users ?? new TestUserStore(TestUsers.Users);
        }
Пример #24
0
        public ExternalController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IEventService events,
            IConfiguration configuration,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _users = users ?? new TestUserStore(TestUsers.Users);

            _interaction   = interaction;
            _clientStore   = clientStore;
            _events        = events;
            _configuration = configuration;

            _userRepo = new UserRepo();
        }
Пример #25
0
 public AccountController(
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     UserManager userManager,
     SignInManager signInManager,
     LogInManager logInManager,
     TestUserStore users = null)
 {
     _interaction       = interaction;
     _clientStore       = clientStore;
     _schemeProvider    = schemeProvider;
     _events            = events;
     this.userManager   = userManager;
     this.signInManager = signInManager;
     this.logInManager  = logInManager;
 }
Пример #26
0
 public AccountController(
     ILogger <AccountController> logger,
     UserManager <User> userManager,
     ICrudService <EmailMessage> emailMessageService,
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     TestUserStore users = null)
 {
     _logger              = logger;
     _userManager         = userManager;
     _emailMessageService = emailMessageService;
     _interaction         = interaction;
     _clientStore         = clientStore;
     _schemeProvider      = schemeProvider;
     _events              = events;
 }
        public async Task RemoveLoginForUser()
        {
            // Create a session and user store for this test.
            var session   = SessionFactory.OpenSession();
            var userStore = new TestUserStore(session);
            // Create and save a user with a login.
            var user = new TestUser {
                UserName = "******"
            };
            var login = new UserLoginInfo("TestProviderRemove", "ProviderKeyRemove", "TestProviderRemove");

            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);

                await userStore.AddLoginAsync(user, login);

                transaction.Commit();
            }
            // Check the user has an id and the login.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Logins.Count, 1);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session   = SessionFactory.OpenSession();
            userStore = new TestUserStore(session);
            // Load the user and remove the login.
            TestUser loadUser;

            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);

                await userStore.RemoveLoginAsync(loadUser, login.LoginProvider, login.ProviderKey);

                transaction.Commit();
            }
            // Check we have the same user and that the login has been removed.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(loadUser.Logins.Count, 0);
        }
Пример #28
0
        public AccountController(
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IHttpContextAccessor httpContextAccessor,
            IEventService events,
            IOptions <ConfigSettingsBase> settings,
            IOptions <ConfigEmailBase> configEmail,

            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            _users         = users ?? new TestUserStore(TestUsers.Users);
            _usersServices = new UserServices();
            _interaction   = interaction;
            _events        = events;
            _settings      = settings;
            _configEmail   = configEmail;
            _account       = new AccountService(interaction, httpContextAccessor, clientStore);
        }
        public async Task GetUserByEmail()
        {
            // Create a session and user store for this test.
            var session   = SessionFactory.OpenSession();
            var userStore = new TestUserStore(session);
            // Create and save a user.
            string userName = "******";
            string email    = "*****@*****.**";
            var    user     = new TestUser {
                UserName = userName, Email = email
            };

            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);

                transaction.Commit();
            }
            // Check the user has an id and a username and email.
            Assert.IsNotNull(user.Id);
            Assert.IsNotNull(user.UserName);
            Assert.IsNotNull(user.Email);

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session   = SessionFactory.OpenSession();
            userStore = new TestUserStore(session);
            // Load the user using the email.
            TestUser loadUser;

            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByEmailAsync(email);

                transaction.Commit();
            }
            // Check we have the same user.
            Assert.AreEqual(user.Id, loadUser.Id);
            Assert.AreEqual(user.UserName, loadUser.UserName);
            Assert.AreEqual(user.Email, loadUser.Email);
        }
        public async Task DeleteUser()
        {
            // Create a session and user store for this test.
            var session   = SessionFactory.OpenSession();
            var userStore = new TestUserStore(session);
            // Create and save a user.
            string userName = "******";
            var    user     = new TestUser {
                UserName = userName
            };

            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);

                transaction.Commit();
            }
            // Check the user has an id and a username.
            Assert.IsNotNull(user.Id);
            Assert.IsNotNull(user.UserName);
            var userId = user.Id;

            // Create a new session and user store so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session   = SessionFactory.OpenSession();
            userStore = new TestUserStore(session);
            // Load and delete the user.
            using (var transaction = session.BeginTransaction())
            {
                user = await userStore.FindByIdAsync(userId);

                await userStore.DeleteAsync(user);

                transaction.Commit();
            }

            // Check that the user has been deleted.
            var deletedUser = await userStore.FindByIdAsync(userId);

            Assert.IsNull(deletedUser);
        }
Пример #31
0
 public AccountController(
     UserManager <AppIdentityUser> userManager,
     SignInManager <AppIdentityUser> signInManager,
     IEmailSender emailSender,
     IIdentityServerInteractionService interaction,
     IClientStore clientStore,
     IHttpContextAccessor httpContextAccessor,
     IAuthenticationSchemeProvider schemeProvider,
     IEventService events,
     TestUserStore users = null)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _emailSender   = emailSender;
     // if the TestUserStore is not in DI, then we'll just use the global users collection
     _users       = users ?? new TestUserStore(TestUsers.Users);
     _interaction = interaction;
     _events      = events;
     _account     = new AccountService(interaction, httpContextAccessor, schemeProvider, clientStore);
 }
Пример #32
0
        public AccountController(
            UserManager <User> userManager,
            SignInManager <User> signInManager,
            IIdentityServerInteractionService interaction,
            IClientStore clientStore,
            IHttpContextAccessor httpContextAccessor,
            IEventService events,
            ILoggerFactory loggerFactory,
            TestUserStore users = null)
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            _users         = users ?? new TestUserStore(TestUsers.Users);
            _interaction   = interaction;
            _events        = events;
            _account       = new AccountService(interaction, httpContextAccessor, clientStore);
            _userManager   = userManager;
            _signInManager = signInManager;

            _logger = loggerFactory.CreateLogger <AccountController>();
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            List <TestUser> userList = new List <TestUser>()
            {
                new TestUser()
                {
                    SubjectId = "1", Password = "******", Username = "******"
                }
            };
            TestUserStore userStore = new TestUserStore(userList);

            //此处使用context.UserName, context.Password 用户名和密码来与数据库的数据做校验
            if (userStore.ValidateCredentials(context.UserName, context.Password))
            {
                var user         = userStore.FindByUsername(context.UserName);
                var resultClaims = new List <Claim>
                {
                    new Claim("测试1", "测试1"),
                    new Claim("测试2", "测试2"),
                    new Claim("测试3", "测试3"),
                    new Claim("测试4", "测试4")
                };
                resultClaims.AddRange(user.Claims);
                //验证通过返回结果
                //subjectId 为用户唯一标识 一般为用户id
                //authenticationMethod 描述自定义授权类型的认证方法
                //authTime 授权时间
                //claims 需要返回的用户身份信息单元 此处应该根据我们从数据库读取到的用户信息 添加Claims 如果是从数据库中读取角色信息,那么我们应该在此处添加
                context.Result = new GrantValidationResult(
                    user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
                    OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
                    resultClaims);
            }
            else
            {
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }
            return(Task.CompletedTask);
        }
Пример #34
0
        public async Task GetUserByLogin()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user with a login.
            var user = new TestUser { UserName = "******" };
            var login = new UserLoginInfo("TestProviderGetUser", "ProviderKeyGetUser");
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                await userStore.AddLoginAsync(user, login);
                transaction.Commit();
            }
            // Check the user has an id and the login.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Logins.Count, 1);

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindAsync(new UserLoginInfo("TestProviderGetUser", "ProviderKeyGetUser"));
                transaction.Commit();
            }
            // Check we have the same user and it has a single login.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(loadUser.Logins.Count, 1);
        }
Пример #35
0
        public async Task GetLoginsForUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user with a login.
            var user = new TestUser { UserName = "******" };
            int numberOfLogins = 5;
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                for (int i = 0; i < numberOfLogins; i++)
                {
                    var login = new UserLoginInfo("TestProviderList" + i, "ProviderKeyRemove" + i);
                    await userStore.AddLoginAsync(user, login);
                }
                transaction.Commit();
            }
            // Check the user has an id and all the logins have been saved.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Logins.Count, numberOfLogins);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            IList<UserLoginInfo> logins;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                logins = await userStore.GetLoginsAsync(user);
                transaction.Commit();
            }
            // Check we have the same user and that they have all of the logins.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(loadUser.Logins.Count, numberOfLogins);
            Assert.AreEqual(logins.Count, numberOfLogins);
        }
Пример #36
0
 public async Task AddLoginForUser()
 {
     // Create a session and user store for this test.
     var session = SessionFactory.OpenSession();
     var userStore = new TestUserStore<TestUser>(session);
     // Create and save a user with a login.
     var user = new TestUser { UserName = "******" };
     var login = new UserLoginInfo("TestProviderAdd", "ProviderKeyAdd");
     using (var transaction = session.BeginTransaction())
     {
         await userStore.CreateAsync(user);
         await userStore.AddLoginAsync(user, login);
         transaction.Commit();
     }
     // Check the user has an id and the login.
     Assert.IsNotNull(user.Id);
     Assert.AreEqual(user.Logins.Count, 1);
 }
Пример #37
0
        public async Task DeleteUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user.
            string userName = "******";
            var user = new TestUser { UserName = userName };
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                transaction.Commit();
            }
            // Check the user has an id and a username.
            Assert.IsNotNull(user.Id);
            Assert.IsNotNull(user.UserName);
            var userId = user.Id;

            // Create a new session and user store so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load and delete the user.
            using (var transaction = session.BeginTransaction())
            {
                user = await userStore.FindByIdAsync(userId);
                await userStore.DeleteAsync(user);
                transaction.Commit();
            }

            // Check that the user has been deleted.
            var deletedUser = await userStore.FindByIdAsync(userId);
            Assert.IsNull(deletedUser);
        }
Пример #38
0
        public async Task GetRolesForAUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            var roleStore = new TestRoleStore<TestRole>(session);
            // Create and save a user and some roles and add the roles to the user.
            int numberOfRoles = 5;
            string roleName = "GetRolesForAUserTestRole";
            var user = new TestUser("GetRolesForAUser");
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                for (int i = 0; i < numberOfRoles; i++)
                {
                    var role = new TestRole(roleName + i);
                    await roleStore.CreateAsync(role);
                    await userStore.AddToRoleAsync(user, role.Name);
                }
                transaction.Commit();
            }
            // Check the user has an Id and the roles.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Roles.Count, numberOfRoles);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            IList<string> roles;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                roles = await userStore.GetRolesAsync(user);
                transaction.Commit();
            }
            // Check we have the same user and it has the role.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(roles.Count, numberOfRoles);
        }
Пример #39
0
        public async Task AddRoleToUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            var roleStore = new TestRoleStore<TestRole>(session);
            // Create and save a role and a user.
            string roleName = "AddRoleToUserTestRole";
            var role = new TestRole(roleName);
            var user = new TestUser("AddRoleToUserTestUser");
            using (var transaction = session.BeginTransaction())
            {
                await roleStore.CreateAsync(role);
                await userStore.CreateAsync(user);
                transaction.Commit();
            }
            // Check the user has an Id and no roles.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Roles.Count, 0);
            var userId = user.Id;
            // Add the user to the role.
            using (var transaction = session.BeginTransaction())
            {
                await userStore.AddToRoleAsync(user, role.Name);
                transaction.Commit();
            }

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                transaction.Commit();
            }
            // Check we have the same user and it has the role.
            Assert.AreEqual(loadUser.Id, user.Id);
            var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName);
            Assert.IsNotNull(userRole);
        }
Пример #40
0
        public async Task RemoveClaimForUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user with a claim.
            var user = new TestUser { UserName = "******" };
            var claimType = ClaimTypes.Role;
            var claimValue = "Admin_RemoveClaimForUserTest";
            var claim = new Claim(claimType, claimValue);
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                await userStore.AddClaimAsync(user, claim);
                transaction.Commit();
            }
            // Check the user has an id and the claim.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Claims.Count, 1);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user and remove the claim.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                await userStore.RemoveClaimAsync(loadUser, claim);
                transaction.Commit();
            }
            // Check we have the same user and it now has no claims.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(loadUser.Claims.Count, 0);
        }
Пример #41
0
 public async Task AddClaimForUser()
 {
     // Create a session and user store for this test.
     var session = SessionFactory.OpenSession();
     var userStore = new TestUserStore<TestUser>(session);
     // Create and save a user with a claim.
     var user = new TestUser { UserName = "******" };
     var claim = new Claim(ClaimTypes.Role, "Admin_AddClaimForUserTest");
     using (var transaction = session.BeginTransaction())
     {
         await userStore.CreateAsync(user);
         await userStore.AddClaimAsync(user, claim);
         transaction.Commit();
     }
     // Check the user has an id and the claim.
     Assert.IsNotNull(user.Id);
     Assert.AreEqual(user.Claims.Count, 1);
 }
Пример #42
0
        public async Task GetUserByIdUsesCache()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user.
            string userName = "******";
            var user = new TestUser { UserName = userName };
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                transaction.Commit();
            }
            // Check the user has an id and a username.
            Assert.IsNotNull(user.Id);
            Assert.IsNotNull(user.UserName);
            var userId = user.Id;

            userStore = new TestUserStore<TestUser>(session);
            // Load the user inside the same session, this should use the cache and not hit the database.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                transaction.Commit();
            }
            // Check we have the same user.
            Assert.AreEqual(user.Id, loadUser.Id);
            Assert.AreEqual(user.UserName, loadUser.UserName);
        }
Пример #43
0
        public async Task GetClaimsForUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user with some claims.
            var user = new TestUser { UserName = "******" };
            int numberOfClaims = 5;
            var claimType = ClaimTypes.Role;
            var claimValue = "Admin_GetClaimsForUserTest";
            var claim = new Claim(claimType, claimValue);
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                await userStore.AddClaimAsync(user, claim);
                for (int i = 0; i < numberOfClaims - 1; i++)
                {
                    var loopClaim = new Claim(claimType, "Admin_GetClaimsForUserTest_" + i);
                    await userStore.AddClaimAsync(user, loopClaim);
                }
                transaction.Commit();
            }
            // Check the user has an id and the claims.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Claims.Count, numberOfClaims);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                transaction.Commit();
            }
            // Check we have the same user and it has the claims.
            Assert.AreEqual(loadUser.Id, user.Id);
            Assert.AreEqual(loadUser.Claims.Count, numberOfClaims);
            var userClaims = await userStore.GetClaimsAsync(loadUser);
            var userClaim = userClaims.SingleOrDefault(c => c.Type == claimType && c.Value == claimValue);
            Assert.IsNotNull(userClaim);
        }
Пример #44
0
        public async Task GetUserByEmail()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user.
            string userName = "******";
            string email = "*****@*****.**";
            var user = new TestUser { UserName = userName, Email = email };
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                transaction.Commit();
            }
            // Check the user has an id and a username and email.
            Assert.IsNotNull(user.Id);
            Assert.IsNotNull(user.UserName);
            Assert.IsNotNull(user.Email);

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user using the email.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByEmailAsync(email);
                transaction.Commit();
            }
            // Check we have the same user.
            Assert.AreEqual(user.Id, loadUser.Id);
            Assert.AreEqual(user.UserName, loadUser.UserName);
            Assert.AreEqual(user.Email, loadUser.Email);
        }
Пример #45
0
        public async Task RemoveRoleFromUserOnlyRemovesSingleRole()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            var roleStore = new TestRoleStore<TestRole>(session);
            // Create and save a role and a user and add the role to the user.
            int numberOfOtherRoles = 3;
            string roleName = "RemoveRoleFromUserOnlyRemovesSingleRole";
            var role = new TestRole(roleName);
            var user = new TestUser("RemoveRoleFromUserOnlyRemovesSingleRole");
            using (var transaction = session.BeginTransaction())
            {
                await roleStore.CreateAsync(role);
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, role.Name);
                for (int i = 0; i < numberOfOtherRoles; i++)
                {
                    var otherRole = new TestRole(roleName + i);
                    await roleStore.CreateAsync(otherRole);
                    await userStore.AddToRoleAsync(user, otherRole.Name);
                }
                transaction.Commit();
            }
            // Check the user has an Id and the roles.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                transaction.Commit();
            }
            // Check we have the same user and it has the role.
            Assert.AreEqual(loadUser.Id, user.Id);
            var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName);
            Assert.IsNotNull(userRole);
            // Now remove the role.
            using (var transaction = session.BeginTransaction())
            {
                await userStore.RemoveFromRoleAsync(loadUser, roleName);
                transaction.Commit();
            }

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user again.            
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                transaction.Commit();
            }
            // Check we have the same user and the role has been removed.
            Assert.AreEqual(loadUser.Id, user.Id);
            userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName);
            Assert.IsNull(userRole);
        }
Пример #46
0
 public async Task GetNonExistingUserByNameReturnsNull()
 {
     // Create a session and user store for this test.
     var session = SessionFactory.OpenSession();
     var userStore = new TestUserStore<TestUser>(session);
     TestUser user;
     using (var transaction = session.BeginTransaction())
     {
         user = await userStore.FindByNameAsync("THISISNOTAUSERNAME");
         transaction.Commit();
     }
     // Check that we have no user.
     Assert.IsNull(user);
 }
Пример #47
0
        public async Task IsInRoleReturnsTrueWhenAUserIsInARoleAndFalseWhenTheyAreNot()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            var roleStore = new TestRoleStore<TestRole>(session);
            // Create and save a role and a user and add the role to the user.
            int numberOfOtherRoles = 3;
            string roleName = "IsInRoleTestRole";
            var role = new TestRole(roleName);
            var user = new TestUser("IsInRoleTestUser");
            using (var transaction = session.BeginTransaction())
            {
                await roleStore.CreateAsync(role);
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, role.Name);
                for (int i = 0; i < numberOfOtherRoles; i++)
                {
                    var otherRole = new TestRole(roleName + i);
                    await roleStore.CreateAsync(otherRole);
                    await userStore.AddToRoleAsync(user, otherRole.Name);
                }
                transaction.Commit();
            }
            // Check the user has an Id and the roles.
            Assert.IsNotNull(user.Id);
            Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1);
            var userId = user.Id;

            // Create a new session and user store for this test, so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load the user.
            TestUser loadUser;
            using (var transaction = session.BeginTransaction())
            {
                loadUser = await userStore.FindByIdAsync(userId);
                transaction.Commit();
            }
            // Check we have the same user and that we get true when testing for the correct role and false for non-existent role.
            Assert.AreEqual(loadUser.Id, user.Id);
            bool inRole = await userStore.IsInRoleAsync(loadUser, roleName);
            bool notInRole = await userStore.IsInRoleAsync(loadUser, "NOTINROLETEST_USERNOTINROLE");
            Assert.IsTrue(inRole);
            Assert.IsFalse(notInRole);
        }
Пример #48
0
        public async Task UpdateUser()
        {
            // Create a session and user store for this test.
            var session = SessionFactory.OpenSession();
            var userStore = new TestUserStore<TestUser>(session);
            // Create and save a user.
            string userName = "******";
            string email = "*****@*****.**";
            var user = new TestUser { UserName = userName };
            using (var transaction = session.BeginTransaction())
            {
                await userStore.CreateAsync(user);
                transaction.Commit();
            }
            // Check the user has an id and a username.
            Assert.IsNotNull(user.Id);
            Assert.IsNotNull(user.UserName);
            Assert.IsNull(user.Email);
            // Update the user's email address.
            using (var transaction = session.BeginTransaction())
            {
                user.Email = email;
                await userStore.UpdateAsync(user);
                transaction.Commit();
            }

            // Create a new session and user store so that we actually hit the database and not the cache.
            userStore.Dispose();
            session.Dispose();
            session = SessionFactory.OpenSession();
            userStore = new TestUserStore<TestUser>(session);
            // Load and update the user.
            TestUser updatedUser;
            using (var transaction = session.BeginTransaction())
            {
                updatedUser = await userStore.FindByIdAsync(user.Id);
                transaction.Commit();
            }

            // Check the email has been updated and saved.
            Assert.AreEqual(updatedUser.Email, email);
        }