private async Task <(UserAuthenticationResult, ActionResult)> HandleEnterpriseUserLogin(string enterpriseUserHeader, string orgNumber)
        {
            EnterpriseUserCredentials credentials;

            try
            {
                credentials = DecodeEnterpriseUserHeader(enterpriseUserHeader, orgNumber);
            }
            catch (Exception)
            {
                return(null, StatusCode(400));
            }

            HttpResponseMessage response = await _enterpriseUserAuthenticationService.AuthenticateEnterpriseUser(credentials);

            string content = await response.Content.ReadAsStringAsync();

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.BadRequest:
                return(null, StatusCode(400));

            case System.Net.HttpStatusCode.NotFound:
                ObjectResult result = StatusCode(401, "The user either does not exist or the password is incorrect.");
                return(null, result);

            case System.Net.HttpStatusCode.TooManyRequests:
                if (response.Headers.RetryAfter != null)
                {
                    Response.Headers.Add("Retry-After", response.Headers.RetryAfter.ToString());
                }

                return(null, StatusCode(429));

            case System.Net.HttpStatusCode.OK:
                UserAuthenticationResult userAuthenticationResult = JsonSerializer.Deserialize <UserAuthenticationResult>(content);

                return(userAuthenticationResult, null);

            default:
                _logger.LogWarning("Unexpected response from SBLBridge during enterprise user authentication. HttpStatusCode={statusCode} Content={content}", response.StatusCode, content);
                return(null, StatusCode(502));
            }
        }
Beispiel #2
0
        public UserAuthenticationResult LoginUser(UserAuthentication userAuthentication, string path)
        {
            var response = new UserAuthenticationResult();

            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            doc.GetElementsByTagName("UserName").Item(0).InnerText = userAuthentication.UserName;
            doc.GetElementsByTagName("Password").Item(0).InnerText = userAuthentication.Password;

            //payload of xml document(Conversion to xml document)
            var stringPayload = new XmlConverter.XmlConverter().ToXml(doc);
            //econding of xml document to UTF-8
            var encodedString = new UTF8Encoding().GetString(stringPayload);

            //replaces xml document footers
            var httpContent = new StringContent(encodedString, Encoding.UTF8, "text/xml");

            using (var httpClient = new HttpClient())
            {
                // Do the actual request and await the response
                var httpResponse =
                    httpClient.PostAsync("http://41.216.173.228/RoboService/UserServicing.asmx?op=RegisterUser", httpContent);

                // If the response contains content we want to read it!
                if (httpResponse.Result.Content != null)
                {
                    if (httpResponse.Result.IsSuccessStatusCode)
                    {
                        //convert back to xml string
                        var         stringData = httpResponse.Result.Content.ReadAsStringAsync().Result;
                        XmlDocument resultDoc  = new XmlDocument();
                        resultDoc.LoadXml(stringData);

                        response.responsecode    = resultDoc.GetElementsByTagName("responsecode").Item(0).InnerText;
                        response.responsemessage = resultDoc.GetElementsByTagName("responsemessage").Item(0).InnerText;
                        response.comment         = resultDoc.GetElementsByTagName("comment").Item(0).InnerText;
                    }
                }
            }

            return(response);
        }
Beispiel #3
0
        /// <summary>
        /// Authenticates the specified credentials with the server, allowing subsequent privileged operations.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns>The returned status code from the server in form of a UserAuthenticationResult</returns>
        public UserAuthenticationResult Authenticate(string username, string password)
        {
            if (Connected)
            {
                byte[] send;
                string hashedPass = Cryptography.GenerateUserHashedPassword(hashKey + username, password);
                ObjectSerialization.Serialize(new LoginData(username, hashedPass), out send);

                // Make a request to the server to register the user. 
                if (MakeBlockingRequest(ref send, PacketType.Authenticate, PacketType.Authenticate))
                {
                    // Deserialize the response.
                    UserAuthenticationResult result = new UserAuthenticationResult();
                    return (UserAuthenticationResult)ObjectSerialization.Deserialize(response, result.GetType());
                }
            }
            return UserAuthenticationResult.UnknownResult; // Who knows what happened.
        }
Beispiel #4
0
 public UserAuthenticatorArgs(string user, string pass)
 {
     User = user;
     Password = pass;
     m_Result = UserAuthenticationResult.Unspecified;
 }
Beispiel #5
0
 public UserAuthenticatorArgs(string user, string pass)
 {
     User     = user;
     Password = pass;
     m_Result = UserAuthenticationResult.Unspecified;
 }
 protected virtual UserAuthenticationResult Authenticate(string userId, string password)
 => userId == password?UserAuthenticationResult.Succeeded() : UserAuthenticationResult.Failed();
Beispiel #7
0
        public IActionResult Post([FromBody] UserAuthenticationRequest model)
        {
            // non-forced-to-disposal
            string response = string.Empty;
            UserAuthenticationResult result = new UserAuthenticationResult
            {
                IsSucceded = true,
                ResultId   = (int)UserAuthenticationResultEnum.Success
            };

            // forced-to-disposal
            MongoDBConnectionInfo mongoDBConnectionInfo = null;
            SymmetricSecurityKey  secretKey             = null;
            SigningCredentials    signinCredentials     = null;
            User user = null;

            try
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    throw new BusinessException((int)UserAuthenticationResultEnum.FailedEmptyEmail);
                }

                if (string.IsNullOrEmpty(model.Password))
                {
                    throw new BusinessException((int)UserAuthenticationResultEnum.FailedEmptyPassword);
                }

                mongoDBConnectionInfo = new MongoDBConnectionInfo()
                {
                    ConnectionString = Settings.ConnectionString,
                    DatabaseId       = Settings.DatabaseId,
                    UserCollection   = Settings.UserCollection
                };

                using (UserAuthenticationDataHelper userAuthenticationDataHelper = new UserAuthenticationDataHelper(mongoDBConnectionInfo))
                {
                    user = userAuthenticationDataHelper.GetUser(model.Email);
                }

                if (user == null)
                {
                    throw new BusinessException((int)UserAuthenticationResultEnum.FailedNotExistsInactiveAccount);
                }

                string password = string.Empty;
                using (HashHelper hh = new HashHelper())
                {
                    password = hh.GetSha256Hash(model.Password);
                }

                if (user.email != model.Email || user.password != password)
                {
                    throw new BusinessException((int)UserAuthenticationResultEnum.FailedIncorrectCredentials);
                }

                secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.AuthorizationKey));
                signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokeOptions = new JwtSecurityToken(
                    issuer: "https://rf.identity.api",
                    audience: "https://rf.identity.api",
                    claims: new List <Claim>(),
                    expires: DateTime.Now.AddDays(1),
                    signingCredentials: signinCredentials
                    );

                response = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
            }
            catch (Exception ex)
            {
                result.IsSucceded = false;

                if (ex is BusinessException)
                {
                    result.ResultId = ((BusinessException)ex).ResultId;
                }
                else
                {
                    result.ResultId = (int)UserAuthenticationResultEnum.Failed;

                    this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            }
            finally
            {
                mongoDBConnectionInfo = null;
                secretKey             = null;
                signinCredentials     = null;
                user = null;

                GC.Collect();
            }

            string message = EnumDescription.GetEnumDescription((UserAuthenticationResultEnum)result.ResultId);

            this.logger.LogInformation($">> Message information: {message}");

            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(new { token = response }) : (ActionResult) new BadRequestObjectResult(new { message = message }));
        }