Пример #1
0
        public ResponseDto <bool> IsHashedCredentialsValid(string username, string password)
        {
            var hasher = new PayloadHasher();

            using (var gateway = new AuthenticationGateway())
            {
                var accountResult = gateway.GetUserAccount(username);

                if (accountResult.Error != null)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = accountResult.Error
                    });
                }

                if (password == accountResult.Data.Password)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = true
                    });
                }
                else
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = AuthenticationErrorMessages.USERNAME_PASSWORD_ERROR
                    });
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Retrieves the id of a first time user's account.
        /// </summary>
        /// <param name="username">User to check</param>
        /// <returns>Id of user</returns>
        private ResponseDto <int?> GetFirstTimeUserAccountId(string username)
        {
            using (var gateway = new AuthenticationGateway())
            {
                var userResult = gateway.GetUserAccount(username);

                if (userResult.Error != null)
                {
                    return(new ResponseDto <int?>()
                    {
                        Error = userResult.Error
                    });
                }

                // If not a first time user, return a general error.
                if (userResult.Data.IsFirstTimeUser.Value != true)
                {
                    return(new ResponseDto <int?>()
                    {
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }

                return(new ResponseDto <int?>()
                {
                    Data = userResult.Data.Id
                });
            }
        }
        private ResponseDto <LoginDto> FailedAttempt(FailedAttempts attempts, string error)
        {
            using (var gateway = new AuthenticationGateway())
            {
                gateway.UpdateFailedAttempt(attempts);
            }

            return(Error(error));
        }
        /// <summary>
        ///
        /// CreateToken
        ///
        /// Creates a new Authentiaction Token and saves it in the Database and return it to the user
        ///
        /// </summary>
        /// <para>
        /// @author: Ahmed Sadiq, Brian Fann, Rachel Dang
        /// @updated: 4/26/18
        /// </para>
        /// <param name="loginDto"></param>
        /// <returns>
        /// Response with the AuthenticationTokenDto
        /// </returns>
        public ResponseDto <AuthenticationTokenDto> CreateToken(string username)
        {
            var tokenHandler        = new JwtSecurityTokenHandler();
            var authenticationToken = new AuthenticationToken();
            var salt = new SaltGenerator().GenerateSalt(128);

            // Creating the Header of the Token
            var key = new SymmetricSecurityKey(Encoding.Default.GetBytes(salt));
            var signingCredentials = new SigningCredentials(key, "HS256");

            authenticationToken.Salt = salt;

            // Assigning the Username to the Token
            authenticationToken.Username = username;

            // Time Stamping the Token
            var issuedOn = DateTime.UtcNow;

            authenticationToken.ExpiresOn = issuedOn.AddMinutes(15);

            // Create claims identity with "Read" permisison claims
            var claimsIdentity = CreateClaimsIdentity(username).Data;

            // Creating the Body of the token
            var tokenDescription = new SecurityTokenDescriptor
            {
                Subject            = claimsIdentity,
                Audience           = AuthenticationTokenConstants.AUDIENCE,
                IssuedAt           = issuedOn,
                Expires            = authenticationToken.ExpiresOn,
                Issuer             = AuthenticationTokenConstants.ISSUER,
                SigningCredentials = signingCredentials,
            };

            // Changing the Token to a String Form
            var token       = tokenHandler.CreateToken(tokenDescription);
            var tokenString = tokenHandler.WriteToken(token);

            authenticationToken.TokenString = tokenString;

            // Storing the Token to the Database
            using (var authenticationGateway = new AuthenticationGateway())
            {
                authenticationGateway.StoreAuthenticationToken(authenticationToken);
            }

            // Assigning the Token to a Dto to return it back to the User
            var authenticationTokenDto = new AuthenticationTokenDto(authenticationToken.Username,
                                                                    authenticationToken.ExpiresOn, authenticationToken.TokenString);

            // Returning the Token to the Controler
            return(new ResponseDto <AuthenticationTokenDto>
            {
                Data = authenticationTokenDto
            });
        }
        public void Should_ReturnNull_When_UserIdIsInvalid()
        {
            // Arrange
            var gateway = new AuthenticationGateway();
            var userId  = 500;

            // Act
            var result = gateway.GetUserPasswordSalt(userId);

            // Assert
            result.Data.Salt.Should().BeNullOrEmpty();
        }
        public void Should_ReturnFailedAttempts_When_UserIsValid_And_HasAttemptedLogin()
        {
            // Arrange
            var gateway  = new AuthenticationGateway();
            var username = "******";

            // Act
            var result = gateway.GetFailedAttempt(username);

            // Assert
            result.Data.Id.Should().NotBeNull();
        }
        public void Should_ReturnUserAccount_When_UserIsValid()
        {
            // Arrange
            var gateway  = new AuthenticationGateway();
            var username = "******";

            // Act
            var result = gateway.GetUserAccount(username);

            // Assert
            result.Data.Should().NotBeNull();
        }
        public void Should_ReturnNull_When_UserIsInvalid_NotUserAccount()
        {
            // Arrange
            var gateway  = new AuthenticationGateway();
            var username = "******";

            //Act
            var result = gateway.GetUserAccount(username);

            //Assert
            result.Data.Should().BeNull();
        }
        private ResponseDto <LoginDto> SuccessfulAttempt(FailedAttempts attempts, LoginDto dto)
        {
            using (var gateway = new AuthenticationGateway())
            {
                gateway.UpdateFailedAttempt(attempts);
            }

            return(new ResponseDto <LoginDto>()
            {
                Data = dto
            });
        }
        public void Should_ReturnPasswordSalt_When_UserIdIsValid()
        {
            // Arrange
            var gateway = new AuthenticationGateway();
            var userId  = 51;

            // Act
            var result = gateway.GetUserPasswordSalt(userId);

            // Assert
            result.Data.Should().BeOfType <PasswordSalt>();
        }
        public void Should_ReturnNull_When_UserIsInvalid_Or_NeverAttemptedLogin()
        {
            // Arrange
            var gateway  = new AuthenticationGateway();
            var username = "******";

            // Act
            var result = gateway.GetFailedAttempt(username);

            // Assert
            result.Data.Should().BeNull();
        }
        /// <summary>
        ///
        /// RevokeToken
        ///
        /// Ends the duration of the token before its Experation time
        ///
        /// </summary>
        /// <param name="authenticationTokenDto"></param>
        /// <returns>
        /// Response with the message of session ending successfully
        /// </returns>
        public ResponseDto <AuthenticationTokenDto> RevokeToken(AuthenticationTokenDto authenticationTokenDto)
        {
            var authenticationTokenPreLogicValidationStrategy =
                new AuthenticationTokenPreLogicValidationStrategy(authenticationTokenDto);

            // Checking if the Dto has all the information it needs
            var validateAuthenticationTokenDtoResult = authenticationTokenPreLogicValidationStrategy.ExcuteStrategy();

            if (validateAuthenticationTokenDtoResult.Error != null)
            {
                return(new ResponseDto <AuthenticationTokenDto>
                {
                    Data = authenticationTokenDto,
                    Error = validateAuthenticationTokenDtoResult.Error
                });
            }

            // Changing the Experiation time on the Token
            authenticationTokenDto.ExpiresOn = DateTime.UtcNow; // Set this to the past

            // Creating the Model to save in the DB
            var incomingAuthenticationToken = new AuthenticationToken(authenticationTokenDto.Username, authenticationTokenDto.ExpiresOn, authenticationTokenDto.TokenString);

            // Validating the Model after creation
            var authenticationTokenPostLogicValidationStrategy =
                new AuthenticationTokenPostLogicValidationStrategy(incomingAuthenticationToken);
            var validateAutenticationTokenResult = authenticationTokenPostLogicValidationStrategy.ExcuteStrategy();

            if (!validateAutenticationTokenResult)
            {
                return(new ResponseDto <AuthenticationTokenDto>
                {
                    Data = authenticationTokenDto,
                    Error = GeneralErrorMessages.GENERAL_ERROR
                });
            }

            // Updating the Token on the Database
            using (var authenticationGateway = new AuthenticationGateway())
            {
                authenticationGateway.StoreAuthenticationToken(incomingAuthenticationToken);
            }

            // Returning a message that everything went fine
            return(new ResponseDto <AuthenticationTokenDto>
            {
                Data = authenticationTokenDto,
            });
        }
        public void Should_ReturnTrue_When_UserIdIsNull_InFailedAttempt()
        {
            // Arrange
            var gateway = new AuthenticationGateway();
            var incomingFailedAttempt = new FailedAttempts()
            {
                LastAttemptTime = DateTime.UtcNow
            };

            // Act
            var result = gateway.UpdateFailedAttempt(incomingFailedAttempt);

            // Assert
            result.Data.Should().BeFalse();
            result.Error.Should().NotBeNullOrEmpty();
        }
        public void Should_ReturnFalse_When_UserNameIsNull_InToken()
        {
            // Arrange
            var gateway = new AuthenticationGateway();
            var incomingAuthenticationToken = new AuthenticationToken()
            {
                TokenString = "TokenString"
            };

            // Act
            var result = gateway.StoreAuthenticationToken(incomingAuthenticationToken);

            // Assert
            result.Data.Should().BeFalse();
            result.Error.Should().NotBeNullOrEmpty();
        }
        public void Should_ReturnFalse_When_UserNameIsValid_NoExpirarionTime_InToken()
        {
            // Arrange
            var gateway = new AuthenticationGateway();
            var incomingAuthenticationToken = new AuthenticationToken()
            {
                Username    = "******",
                TokenString = "TokenString",
            };

            // Act
            var result = gateway.StoreAuthenticationToken(incomingAuthenticationToken);

            // Assert
            result.Data.Should().BeFalse();
            result.Error.Should().NotBeNullOrEmpty();
        }
        public void Should_ReturnTrue_When_UserNameIsValid_InToken()
        {
            // Arrange
            var gateway = new AuthenticationGateway();
            var incomingAuthenticationToken = new AuthenticationToken()
            {
                Username    = "******",
                TokenString = "TokenString",
                ExpiresOn   = DateTime.UtcNow
            };

            // Act
            var result = gateway.StoreAuthenticationToken(incomingAuthenticationToken);

            // Assert
            result.Data.Should().BeTrue();
            result.Error.Should().BeNullOrEmpty();
        }
 public MyService(SingleSignOnRegistry registry, AuthenticationGateway authGateway)
 {
     _ssoRegistry = registry;
     _authGateway = authGateway;
 }
 public AuthenticationManager()
 {
     authenticationGateway = new AuthenticationGateway();
     userGateway           = new UserGateway();
 }
Пример #19
0
        protected IList <Cookie> Authenticate(IAccount account)
        {
            IList <Cookie> cookies = AuthenticationGateway.Authenticate(account);

            return(cookies);
        }
Пример #20
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                AuthenticationTokenManager tokenManager = new AuthenticationTokenManager();
                AuthenticationToken        authenticationToken;
                TokenService tokenService = new TokenService();

                // Check if the request URI absolute path should skip authentication
                if (CheckIfSkippedUri(request.RequestUri.AbsolutePath.ToLower()))
                {
                    return(await base.SendAsync(request, cancellationToken));
                }

                // Send request when request has no token
                if (request.Headers.Authorization == null)
                {
                    return(await base.SendAsync(request, cancellationToken));
                }

                // Extracting the tokenString from the Header
                var tokenString = tokenService.ExtractToken(request);

                // Checking if there is an empty or a null value to the token
                if (string.IsNullOrEmpty(tokenString))
                {
                    // This is done incase the request does not require authentication
                    return(await base.SendAsync(request, cancellationToken));
                }


                // Extract username from  the token
                var username = tokenService.GetTokenUsername(tokenString);

                // Checking if the Username is empty or null
                if (string.IsNullOrEmpty(username))
                {
                    return(await Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Unauthorized), cancellationToken));
                }

                using (AuthenticationGateway gateway = new AuthenticationGateway())
                {
                    // Getting the Authentication Token Associated with the username
                    var gatewayResult = gateway.GetAuthenticationToken(username);

                    if (gatewayResult.Error != null || gatewayResult.Data.TokenString != tokenString || gatewayResult.Data.ExpiresOn.CompareTo(DateTime.Now) < 0)
                    {
                        return(await Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Unauthorized), cancellationToken));
                    }

                    authenticationToken = gatewayResult.Data;
                }

                var tokenPrincipal = tokenManager.GetTokenPrincipal(authenticationToken, out _);

                Thread.CurrentPrincipal = tokenPrincipal;

                return(await base.SendAsync(request, cancellationToken));
            }
            catch (Exception)
            {
                return(await Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Unauthorized), cancellationToken));
            }
        }
        /// <summary>
        /// This Method contains all the logic that is implemented to authenticate the user with the database
        /// </summary>
        /// <param name="loginDto"></param>
        /// <returns>
        /// ResponseDto with the updated LoginDto
        /// </returns>
        public ResponseDto <LoginDto> LoginUser(LoginDto loginDto)
        {
            var loginPreLogicValidationStrategy = new LoginPreLogicValidationStrategy(loginDto);

            // Checking if the Dto has all the information it needs
            var validateLoginDtoResult = loginPreLogicValidationStrategy.ExecuteStrategy();

            if (!validateLoginDtoResult.Data)
            {
                return(new ResponseDto <LoginDto>
                {
                    Error = validateLoginDtoResult.Error
                });
            }

            // Pulling attempts from DB
            using (var gateway = new AuthenticationGateway())
            {
                var userAttemptsResult = gateway.GetFailedAttempt(loginDto.Username);
                // Checking if the gateway returns a false
                if (userAttemptsResult.Error != null)
                {
                    return(Error(userAttemptsResult.Error));
                }
                // If there is no Error then take the data out
                var userAttempts = userAttemptsResult.Data;

                // Checking if they already have 5 failed attempts 20 mins ago
                if (userAttempts == null)
                {
                    userAttempts = new FailedAttempts()
                    {
                        LastAttemptTime = DateTime.UtcNow,
                        Count           = 0
                    };
                }
                else if (userAttempts.Count >= 5)
                {
                    var timeToCompare = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(20));
                    if (!(userAttempts.LastAttemptTime.CompareTo(timeToCompare) < 0))
                    {
                        return(Error(AuthenticationErrorMessages.LOCKED_ACCOUNT));
                    }
                    userAttempts.Count = 0;
                }

                // Pull the User From DB
                // Getting the user's ID
                var userAccountResult = gateway.GetUserAccount(loginDto.Username);
                if (userAccountResult.Error != null)
                {
                    return(Error(userAccountResult.Error));
                }

                // If there are no Errors from the gateway assign the data to an object
                var userAccount = userAccountResult.Data;
                // Set UserAttempts Id with the UserAccount Id
                userAttempts.Id = userAccount.Id;

                // Getting the Salt associated with the ID
                var saltResult = gateway.GetUserPasswordSalt(userAccount.Id);
                if (saltResult.Error != null)
                {
                    return(Error(userAccountResult.Error));
                }

                // Check if user is Active
                if (userAccount.IsActive == null || userAccount.IsActive == false)
                {
                    return(Error(AuthenticationErrorMessages.INACTIVE_USER));
                }

                var password = loginDto.Password;
                // Hash and Salting the Password
                var hashedPassword = new PayloadHasher().Sha256HashWithSalt(saltResult.Data.Salt, password);

                // Checking if the Password is equal to what is in the DataBase
                var checkPasswordResult = hashedPassword == userAccount.Password;

                // If Password matches log the attempt and send loginDto back
                if (checkPasswordResult)
                {
                    userAttempts.Count = 0;
                    return(SuccessfulAttempt(userAttempts, loginDto));
                }

                // Checking if this is the 5th attempt to time stamp it
                if (++userAttempts.Count >= 5)
                {
                    userAttempts.LastAttemptTime = DateTime.UtcNow;
                }

                return(FailedAttempt(userAttempts, AuthenticationErrorMessages.USERNAME_PASSWORD_ERROR));
            }
        }
Пример #22
0
        /// <summary>
        /// Validates whether the payload's credentials are valid.
        /// <para>
        /// @author: Brian Fann
        /// @updated: 4/24/18
        /// </para>
        /// </summary>
        /// <param name="payload">Payload of token</param>
        /// <returns>True if credentials are valid, false otherwise</returns>
        private ResponseDto <bool> ValidateCredentials(SsoTokenPayloadDto payload)
        {
            // Validate username and password
            var loginDto = new LoginDto(payload.Username, payload.Password);
            var accountValidationStrategy = new LoginPreLogicValidationStrategy(loginDto);
            var accountResult             = accountValidationStrategy.ExecuteStrategy();

            if (!accountResult.Data)
            {
                StoreInvalidToken();

                return(new ResponseDto <bool>()
                {
                    Data = false,
                    Error = accountResult.Error
                });
            }

            using (var gateway = new AuthenticationGateway())
            {
                var userAccountResult = gateway.GetUserAccount(payload.Username);

                if (userAccountResult.Error != null)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = userAccountResult.Error
                    });
                }

                var userAccount = userAccountResult.Data;

                var saltResult = gateway.GetUserPasswordSalt(userAccount.Id);

                // Check if salt exists
                if (saltResult.Error != null)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = saltResult.Error
                    });
                }

                // Hash the password and compare it against the database
                var hashedPassword     = new PayloadHasher().Sha256HashWithSalt(saltResult.Data.Salt, payload.Password);
                var isPasswordMatching = hashedPassword == userAccount.Password;

                if (!isPasswordMatching)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = AuthenticationErrorMessages.USERNAME_PASSWORD_ERROR
                    });
                }
            }

            // Credentials are valid at this point
            return(new ResponseDto <bool>()
            {
                Data = true
            });
        }