public AuthenticateResponseDto Authenticate(UserCredentialsViewModel credentialsViewModel)
        {
            using (AuthenticationExampleDbContext context = new AuthenticationExampleDbContext())
            {
                UserDto userDto = new UserCredentialsValidator(context).CredentialsIsValid(new UserCredentialsDto
                {
                    UserName = credentialsViewModel.UserName,
                    Password = credentialsViewModel.Password
                });

                if (userDto != null)
                {
                    return(new AuthenticateResponseDto
                    {
                        SecureToken = new TokenBuilder(context).TokenBuild(new LoggedUserDto
                        {
                            UserId = userDto.Id,
                            UserName = userDto.UserName,
                            Password = credentialsViewModel.Password
                        })
                    });
                }
            }

            throw new WebFaultException <RequestErrorDto>(
                      new RequestErrorDto
            {
                StatusCode = (int)HttpStatusCode.Forbidden,
                Reason     = "Authentication Error!",
                Details    = "Username/ password pair is incorrect!"
            }, HttpStatusCode.Unauthorized);
        }
        public IActionResult SignInWithToken([FromBody] UserCredentials userCreds)
        {
            UserCredentialsValidator validator = new UserCredentialsValidator();
            var results = validator.Validate(userCreds);

            var errors = results.ToString("\n");

            if (errors != string.Empty)
            {
                var errorList = ErrorFormatter.FormatValidationErrors(errors);
                return(BadRequest(new { Errors = errorList }));
            }

            try
            {
                // By default we return only if the user has curretn tenant in active tenants.
                // If the user is not active in current tenant, we will return not found
                User user = _repository.GetUser(userCreds.EmailAddress);
                if (user == null)
                {
                    return(NotFound("User not found or has not access"));
                }


                bool isValidUser = _repository.ValidatePassword(userCreds, user);
                if (!isValidUser)
                {
                    return(Unauthorized());
                }

                var token = _tokenManager.GenerateNewToken(user);

                return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }));
            } catch (Exception e)
            {
                _logger.LogError($"Could not create JWT. Error: ${e}");
            }

            return(BadRequest("Failed to signin. Coud not generate token"));
        }
Beispiel #3
0
        private static void BasicAuthenticationValidation()
        {
            string authorizationHeaderAttribute = WebOperationContext.Current?.IncomingRequest.Headers["Authorization"];

            if (!string.IsNullOrWhiteSpace(authorizationHeaderAttribute))
            {
                using (AuthenticationExampleDbContext context = new AuthenticationExampleDbContext())
                {
                    BasicAuthenticationDecoder basicAuthenticationDecoder =
                        new BasicAuthenticationDecoder(authorizationHeaderAttribute);

                    UserDto userDto = new UserCredentialsValidator(context).CredentialsIsValid(basicAuthenticationDecoder.GetUserCredentials());

                    if (userDto == null)
                    {
                        throw new WebFaultException <RequestErrorDto>(
                                  new RequestErrorDto
                        {
                            StatusCode = (int)HttpStatusCode.Unauthorized,
                            Reason     = "Permission Denied! ",
                            Details    = "The User Credentials are incorrect or the cookie has been changed. (Change suspected!)"
                        }, HttpStatusCode.Unauthorized);
                    }

                    WebOperationContext.Current.IncomingRequest.Headers.Add("UserID", userDto.Id.ToString());
                    WebOperationContext.Current.IncomingRequest.Headers.Add("UserName", userDto.UserName);
                }
            }
            else
            {
                throw new WebFaultException <RequestErrorDto>(
                          new RequestErrorDto
                {
                    StatusCode = (int)HttpStatusCode.Forbidden,
                    Reason     = "Permission Denied!",
                    Details    = "Please sign in to access this service!"
                }, HttpStatusCode.Forbidden);
            }
        }
Beispiel #4
0
        private bool ValidateData()
        {
            UserCredentialsValidator validator = new UserCredentialsValidator();

            if (!validator.ValidateName(FirstName))
            {
                Error = "Imię nie może byc puste";
                return(false);
            }
            if (!validator.ValidateName(LastName))
            {
                Error = "Nazwisko nie może być puste";
                return(false);
            }
            string message;

            if (!validator.ValidateEmail(Email, out message))
            {
                Error = message;
                return(false);
            }
            return(true);
        }
    // todo: the model should never contain the salt!  It stays behind the service layer.
    //public string UserId { get; set; }

    public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
      var validator = new UserCredentialsValidator();
      var result = validator.Validate(this);
      return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
    }
 public void SetUp()
 {
     _validator = new UserCredentialsValidator(new UserRepository());
 }