Esempio n. 1
0
        public async void TestUserLogin_UpdatesLastLoginByClient()
        {
            var userLoginManager = new UserLoginManager(UserStore, new Mock <ILogger>().Object);

            var userId     = $"HealthCatalyst\\{GetRandomString()}";
            var provider   = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            var clientId   = "sampleApp";
            var userName   = "******";
            var firstName  = "foo";
            var lastName   = "baz";
            var middleName = "dot";
            var claims     = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtClaimTypes.GivenName, firstName),
                new Claim(JwtClaimTypes.FamilyName, lastName),
                new Claim(JwtClaimTypes.MiddleName, middleName),
                new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Viewer")
            };

            var user = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            var firstLoginDate = user.LastLoginDatesByClient.First().LoginDate;

            //Sleep to ensure some time passes between logins
            Thread.Sleep(10);

            user = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            var secondLoginDate = user.LastLoginDatesByClient.First().LoginDate;

            Assert.True(secondLoginDate >= firstLoginDate, "second login date is not greater than first");
        }
Esempio n. 2
0
        public async void TestUserLogin_UpdateClaims_RemovesClaim()
        {
            var userLoginManager = new UserLoginManager(UserStore, new Mock <ILogger>().Object);
            var userId           = $"HealthCatalyst\\{GetRandomString()}";
            var provider         = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            var clientId         = "sampleApp";
            var claims           = GetBaseClaims();

            claims.Add(new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Editor"));

            await userLoginManager.UserLogin(provider, userId, claims, clientId);

            var storedUser = UserStore.FindBySubjectIdAsync(userId).Result;

            Assert.Equal(claims.Count, storedUser.Claims.Count);

            var claim = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Role);

            claims.Remove(claim);
            await userLoginManager.UserLogin(provider, userId, claims, clientId);

            storedUser = UserStore.FindBySubjectIdAsync(userId).Result;
            Assert.Equal(claims.Count, storedUser.Claims.Count);
            Assert.Equal(claims.First(c => c.Type == ClaimTypes.Name).Value, storedUser.Claims.First(c => c.Type == JwtClaimTypes.Name).Value);
            Assert.Equal(claims.First(c => c.Type == JwtClaimTypes.GivenName).Value, storedUser.Claims.First(c => c.Type == JwtClaimTypes.GivenName).Value);
            Assert.Equal(claims.First(c => c.Type == JwtClaimTypes.FamilyName).Value, storedUser.Claims.First(c => c.Type == JwtClaimTypes.FamilyName).Value);
            Assert.Equal(claims.First(c => c.Type == JwtClaimTypes.MiddleName).Value, storedUser.Claims.First(c => c.Type == JwtClaimTypes.MiddleName).Value);
            Assert.Equal(claims.Count(c => c.Type == JwtClaimTypes.Role), storedUser.Claims.Count(c => c.Type == JwtClaimTypes.Role));
            Assert.Equal(1, storedUser.Claims.Count(c => c.Type == JwtClaimTypes.Role));
        }
        public async Task UserLoginManager_UserLogin_ExistingUser_HasPropertiesAndRoleClaimsUpdated()
        {
            var documentDbUserStore = new InMemoryUserStore(new InMemoryDocumentService());

            var userLoginManager = new UserLoginManager(documentDbUserStore, new Mock <ILogger>().Object);

            var userId     = "HealthCatalyst\\foo.bar";
            var provider   = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            var clientId   = "sampleApp";
            var userName   = "******";
            var firstName  = "foo";
            var lastName   = "bar";
            var middleName = "dot";
            var claims     = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtClaimTypes.GivenName, firstName),
                new Claim(JwtClaimTypes.FamilyName, lastName),
                new Claim(JwtClaimTypes.MiddleName, middleName),
                new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Viewer")
            };

            var existingUser = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            var existingRoleClaim = existingUser.Claims.Single(c => c.Type == JwtClaimTypes.Role);
            var firstLoginDate    = existingUser.LastLoginDatesByClient.First().LoginDate;

            userId     = "HealthCatalyst\\foo.bar";
            provider   = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            clientId   = "sampleApp";
            userName   = "******";
            firstName  = "abc";
            lastName   = "def";
            middleName = "zzz";
            claims     = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtClaimTypes.GivenName, firstName),
                new Claim(JwtClaimTypes.FamilyName, lastName),
                new Claim(JwtClaimTypes.MiddleName, middleName),
                new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Editor")
            };

            var updatedUser = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            Assert.Equal(userName, updatedUser.Username);
            Assert.Equal(firstName, updatedUser.FirstName);
            Assert.Equal(lastName, updatedUser.LastName);
            Assert.Equal(middleName, updatedUser.MiddleName);
            Assert.Equal(5, updatedUser.Claims.Count);
            Assert.NotEqual(existingRoleClaim.Value, updatedUser.Claims.First().Value);
            Assert.True(firstLoginDate.Ticks < updatedUser.LastLoginDatesByClient.First().LoginDate.Ticks);
        }
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    AuthenticationProperties props = null;
                    // only set explicit expiration here if persistent.
                    // otherwise we reply upon expiration configured in cookie middleware.
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    var user = _users.FindByUsername(model.Username);
                    //get the client id from the auth context
                    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                    await _userLoginManager.UserLogin("test", user.SubjectId, user.Claims.ToList(), context?.ClientId);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));

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

                    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await _accountService.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
        public async Task UserLoginManager_UserLogin_NewUserWithTwoNameClaims()
        {
            var userLoginManager = new UserLoginManager(
                new InMemoryUserStore(new InMemoryDocumentService()),
                new Mock <ILogger>().Object);

            var subjectId         = Guid.NewGuid().ToString();
            var clientId          = "test";
            var userPrincipalName = "*****@*****.**";
            var userDisplayName   = "Bob Gomez";

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userPrincipalName),
                new Claim(JwtClaimTypes.Name, userDisplayName),
                new Claim(FabricIdentityConstants.PublicClaimTypes.UserPrincipalName, userPrincipalName)
            };

            var newUser = await userLoginManager.UserLogin(FabricIdentityConstants.AuthenticationSchemes.Azure,
                                                           subjectId, claims, clientId);

            var nameClaims = newUser.Claims.Where(c => c.Type == JwtClaimTypes.Name).ToList();

            Assert.Equal(subjectId, newUser.SubjectId);
            Assert.Equal(userPrincipalName, newUser.Username);
            Assert.Equal(1, nameClaims.Count);
            Assert.Equal(userDisplayName, nameClaims.Single().Value);
        }
        public async Task UserLoginManager_UserLogin_NoNameOrUpnClaim()
        {
            var userLoginManager = new UserLoginManager(
                new InMemoryUserStore(new InMemoryDocumentService()),
                new Mock <ILogger>().Object);

            var subjectId = Guid.NewGuid().ToString();
            var clientId  = "test";

            var claims  = new List <Claim>();
            var newUser = await userLoginManager.UserLogin(FabricIdentityConstants.AuthenticationSchemes.Azure,
                                                           subjectId, claims, clientId);

            Assert.Equal(subjectId, newUser.SubjectId);
            Assert.Equal(subjectId, newUser.Username);
        }
        public async Task UserLoginManager_UserLogin_NewUser_HasCorrectPropertiesSet()
        {
            //create a new user, ensure claims,  login date, provider, and name properties are set correctly
            var userLoginManager = new UserLoginManager(
                new InMemoryUserStore(new InMemoryDocumentService()),
                new Mock <ILogger>().Object);

            var userId     = "HealthCatalyst\\foo.baz";
            var provider   = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            var clientId   = "sampleApp";
            var userName   = "******";
            var firstName  = "foo";
            var lastName   = "baz";
            var middleName = "dot";
            var claims     = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtClaimTypes.GivenName, firstName),
                new Claim(JwtClaimTypes.FamilyName, lastName),
                new Claim(JwtClaimTypes.MiddleName, middleName),
                new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Viewer")
            };

            var newUser = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            Assert.Equal(userId, newUser.SubjectId);
            Assert.Equal(provider, newUser.ProviderName);
            Assert.Equal(userName, newUser.Username);
            Assert.Equal(firstName, newUser.FirstName);
            Assert.Equal(lastName, newUser.LastName);
            Assert.Equal(middleName, newUser.MiddleName);
            Assert.Equal(5, newUser.Claims.Count);
            Assert.Equal(1, newUser.Claims.Count(c => c.Type == JwtClaimTypes.Name));
            Assert.Equal(1, newUser.Claims.Count(c => c.Type == JwtClaimTypes.Role));
            Assert.Equal(1, newUser.LastLoginDatesByClient.Count);
            Assert.Equal(clientId, newUser.LastLoginDatesByClient.First().ClientId);
        }