public async Task <IActionResult> LoginByUsernameAsync([FromBody] LoginByUsernameViewModelRequest login) { ViewModelResponse <LoginViewModelResponse> viewModelResponse = new ViewModelResponse <LoginViewModelResponse>() { Success = false, ErrorMessage = string.Empty, ErrorCode = string.Empty }; User user = null; JwtToken jwtToken = null; string name = string.Empty; string role = string.Empty; string issuer = string.Empty; string audience = string.Empty; string key = string.Empty; int expires = 0; try { // Get user by username and password user = await _userService.GetByUsernameAsync(login.Username, login.Password); // Validate if the user exists if (user == null) { viewModelResponse.ErrorMessage = CoreConstant.MESSAGE_USERNAME_PASSWORD_INVALID; viewModelResponse.ErrorCode = CoreConstant.CODE_USERNAME_PASSWORD_INVALID; return(BadRequest(viewModelResponse)); } // Set values for create token name = user.Username; role = user.UserRoles.FirstOrDefault().Role.Denomination; issuer = _configuration["Tokens:Issuer"]; audience = _configuration["Tokens:Issuer"]; key = _configuration["JWT:Key"]; expires = int.Parse(_configuration["Jwt:Expires"]); // Get token jwtToken = await _jwtTokenService.GenerateTokenAsync(name, role, issuer, audience, expires, key); if (jwtToken == null) { viewModelResponse.ErrorMessage = CoreConstant.MESSAGE_TOKEN_INVALID; viewModelResponse.ErrorCode = CoreConstant.CODE_TOKEN_INVALID; return(BadRequest(viewModelResponse)); } await _jwtTokenService.AddAsync(jwtToken); } catch (Exception ex) { throw ex; } return(Ok(viewModelResponse)); }