Exemplo n.º 1
0
        /// <summary>
        /// Validates the client.
        /// </summary>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="loginMessage">The login message.</param>
        /// <param name="client">The client.</param>
        /// <returns>is valid client</returns>
        private static bool ValidateClient(string clientId, ref string loginMessage, out AuthClient client)
        {
            client = null;

            if (string.IsNullOrEmpty(clientId))
            {
                loginMessage = "Client id should be sent.";
                return(false);
            }
            else
            {
                client = AuthenticationCommands.FindAuthClient(clientId);
            }

            if (client == null)
            {
                loginMessage = string.Format("Client '{0}' is not registered in the system.", clientId);
                return(false);
            }
            else
            {
                if (!client.IsActive)
                {
                    loginMessage = string.Format("Client {0} is inactive.", client.Id);
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 2
0
        public async Task <HttpResponseMessage> SwitchOrganization(Login loginModel)
        {
            string pswd = string.Empty;

            if (ApiContext.ActiveUser.OrganizationId != loginModel.OrganizationId)
            {
                pswd = Business.Common.CommonCommands.SwitchOrganization(ApiContext.ActiveUser, loginModel.OrganizationId); // Updating default Role
                AuthenticationCommands.SetTokenExpires();
                HttpRequest request         = HttpContext.Current.Request;
                string      tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/Token";
                loginModel.Password       = SecureString.Decrypt(pswd);
                loginModel.OrganizationId = loginModel.OrganizationId;
                using (var client = new HttpClient())
                {
                    var requestParams = new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("username", loginModel.Username),
                        new KeyValuePair <string, string>("password", loginModel.Password),
                        new KeyValuePair <string, string>("organizationId", loginModel.OrganizationId.ToString())
                    };

                    if (string.IsNullOrEmpty(loginModel.ClientId) == false)
                    {
                        requestParams.Add(new KeyValuePair <string, string>("client_id", loginModel.ClientId));
                    }

                    if (loginModel.ForceLogin)
                    {
                        requestParams.Add(new KeyValuePair <string, string>("forceLogin", loginModel.ForceLogin.ToString()));
                    }

                    if (loginModel.RememberMe)
                    {
                        requestParams.Add(new KeyValuePair <string, string>("rememberMe", loginModel.RememberMe.ToString()));
                    }

                    var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
                    var tokenServiceResponse        = client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded).Result;

                    if (tokenServiceResponse.IsSuccessStatusCode)
                    {
                        var accessToken = tokenServiceResponse.Content.ReadAsAsync <Token>().Result;
                        HttpResponseMessage successResponse = Request.CreateResponse(HttpStatusCode.OK, accessToken);
                        return(successResponse);
                    }
                    else
                    {
                        var responseString = tokenServiceResponse.Content.ReadAsStringAsync();
                        HttpResponseMessage failedResponse = Request.CreateResponse(tokenServiceResponse.StatusCode);
                        failedResponse.Content = new StringContent("failed", Encoding.UTF8, "application/json");
                        return(failedResponse);
                    }
                }
            }
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.PreconditionFailed);

            response.Content = new StringContent("failed", Encoding.UTF8, "application/json");
            return(response);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Handles the OnAuthenticate event of the FormsAuthentication control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="FormsAuthenticationEventArgs"/> instance containing the event data.</param>
        public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
        {
            if (args == null)
            {
                return;
            }
            try
            {
                if (Request.Cookies[SimplexRestAuthenticationModule.CookieName] != null)
                {
                    args.User = AuthenticationCommands.AuthenticateTicket(Request.Cookies[SimplexRestAuthenticationModule.CookieName].Value);

                    // Add the details in the cookis which is uesed to navigate to the details page in case of opening from other application (CC)
                    if (Request.QueryString["ReturnUrl"] != null && Request.QueryString["ReturnUrl"].Contains("VendorBillDetails"))
                    {
                        var authCookie = new HttpCookie("ReturnUrl", Request.QueryString["ReturnUrl"].ToString());

                        // Removed Remember Me support due to ticket expiration conflict
                        HttpContext.Current.Response.Cookies.Add(authCookie);
                    }
                }
                else if (Request.QueryString[SimplexRestAuthenticationModule.CookieName] != null && !string.IsNullOrEmpty(Request.QueryString[SimplexRestAuthenticationModule.CookieName]))
                {
                    // Authenticate the external tickets
                    args.User = AuthenticationCommands.AuthenticateTicket(Request.QueryString[SimplexRestAuthenticationModule.CookieName].ToString());
                    if (args.User.Identity.IsAuthenticated)
                    {
                        if (Request.Cookies[SimplexRestAuthenticationModule.CookieName] == null)
                        {
                            var authCookie = new HttpCookie(SimplexRestAuthenticationModule.CookieName, Request.QueryString[SimplexRestAuthenticationModule.CookieName].ToString());

                            // Removed Remember Me support due to ticket expiration conflict
                            HttpContext.Current.Response.Cookies.Add(authCookie);
                        }

                        if (Request.QueryString["ReturnUrl"] != null)
                        {
                            var authCookie = new HttpCookie("ReturnUrl", Request.QueryString["ReturnUrl"].ToString());

                            // Removed Remember Me support due to ticket expiration conflict
                            HttpContext.Current.Response.Cookies.Add(authCookie);
                        }
                    }
                }
            }
            catch (ExpiredTicketException)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
            }
            catch (AuthenticationException)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
            }
        }
Exemplo n.º 4
0
        public static int CreateUser(string username = "******", string password = "******", bool addGroup = false, bool createResource = false)
        {
            var userId = AuthenticationCommands.CreateSecurityUser(username, "*****@*****.**");

            AuthenticationCommands.SetPassword(userId, password);

            if (addGroup)
            {
                AddUserToGroup(userId);
            }

            if (createResource)
            {
                CreateLogicalResource();
            }

            return(userId);
        }
Exemplo n.º 5
0
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var verifiedAccessToken = await CommonValidations.VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken);

            if (verifiedAccessToken == null)
            {
                return(BadRequest("Invalid Provider or External Access Token"));
            }

            UserIdentity userIdentity = AuthenticationCommands.FindLoginProvider(model.Provider, verifiedAccessToken.user_id);

            bool hasRegistered = userIdentity != null;

            if (hasRegistered)
            {
                return(BadRequest("External user is already registered"));
            }

            var userId = AuthenticationCommands.AddUser(model.UserName, model.Password);

            if (userId < 1)
            {
                return(BadRequest("Unable to create user."));
            }

            var authProvider = new AuthProvider
            {
                LoginProvider = model.Provider,
                ProviderKey   = verifiedAccessToken.user_id,
                UserId        = userId
            };

            var isInserted = AuthenticationCommands.AddNewUserLoginProvider(authProvider);

            //generate access token response
            var accessTokenResponse = Helper.GenerateLocalAccessTokenResponse(AuthenticationCommands.FindUserByUserId(userId));

            return(Ok(accessTokenResponse));
        }
Exemplo n.º 6
0
        public async Task <IHttpActionResult> ObtainLocalAccessToken(string provider, string externalAccessToken)
        {
            if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(externalAccessToken))
            {
                return(BadRequest("Provider or external access token is not sent"));
            }

            var verifiedAccessToken = await CommonValidations.VerifyExternalAccessToken(provider, externalAccessToken);

            if (verifiedAccessToken == null)
            {
                return(BadRequest("Invalid Provider or External Access Token"));
            }

            UserIdentity userIdentity = AuthenticationCommands.FindLoginProvider(provider, verifiedAccessToken.user_id);

            bool hasRegistered = userIdentity != null;

            if (!hasRegistered)
            {
                return(BadRequest("External user is not registered"));
            }

            string authToken = AuthenticationCommands.GenerateAuthToken(userIdentity.Username, !ApiSecurity.Configuration.Current.MultipleInstanceEnabled);

            if (string.IsNullOrEmpty(authToken))
            {
                return(BadRequest(string.Format("The user {0}, is already logged in with other device/machine.", userIdentity.Username)));
            }
            else
            {
                userIdentity.UserAuthTokenId = authToken;
            }

            //generate access token response
            var accessTokenResponse = Helper.GenerateLocalAccessTokenResponse(userIdentity);

            return(Ok(accessTokenResponse));
        }
Exemplo n.º 7
0
        private void ProcessResponse(string response)
        {
            if (!_greetSent)
            {
                return;
            }

            switch (CaptureData)
            {
            case 1:
                TransactionCommands.ProcessData(this, response);
                return;

            case 2:
            case 3:
            case 4:
                AuthenticationCommands.ProcessData(this, response.Trim());
                return;
            }

            response = response.Trim();

            string command;
            var    data = string.Empty;

            if (response.Contains(":"))
            {
                command = response.Substring(0, response.IndexOf(":", StringComparison.Ordinal)).ToUpper().TrimEnd();
            }
            else if (response.Contains(" "))
            {
                command = response.Substring(0, response.IndexOf(" ", StringComparison.Ordinal)).ToUpper().TrimEnd();
            }
            else
            {
                command = response.ToUpper();
            }

            if (command.Length != response.Length)
            {
                data = response.Substring(command.Length).TrimStart();
            }

            switch (command)
            {
            case "EHLO":
                Transaction      = null;
                _protocolVersion = 2;
                WriteText($"250-{Server.Options.ServerName} at your service");
                if (Server.AuthLogin != null)
                {
                    WriteText("250-AUTH LOGIN PLAIN");
                }
                if (!Secure && Server.Certificate != null)
                {
                    WriteText("250-STARTTLS");
                }
                WriteText("250 8BITMIME");
                break;

            case "HELO":
                Transaction      = null;
                _protocolVersion = 1;
                WriteText($"250 {Server.Options.ServerName} at your service");
                break;

            case "STARTTLS":
                if (Secure)
                {
                    WriteCode(503, "5.5.1");
                    return;
                }

                if (Server.Certificate == null)
                {
                    WriteCode(502, "5.5.1");
                    return;
                }

                WriteCode(220, "2.0.0", "Ready for TLS");

                _stream    = new SslStream(_innerStream, false);
                Secure     = true;
                Encryption = ConnectionEncryption.StartTls;
                ((SslStream)_stream).AuthenticateAsServer(Server.Certificate, false, Server.Options.Protocols, true);
                _reader = new StreamReader(_stream);
                break;

            case "HELP":
                WriteCode(214, "2.0.0");
                break;

            case "AUTH":
                if (_protocolVersion == 0)
                {
                    WriteCode(503, "5.5.1", "EHLO/HELO first.");
                    return;
                }
                AuthenticationCommands.ProcessCommand(this, data);
                break;

            case "NOOP":
                WriteCode(250, "2.0.0");
                break;

            case "QUIT":
                WriteCode(221, "2.0.0");
                Dispose();
                break;

            case "RSET":
            case "MAIL FROM":
            case "RCPT TO":
            case "DATA":
                if (_protocolVersion == 0)
                {
                    WriteCode(503, "5.5.1", "EHLO/HELO first.");
                    return;
                }
                TransactionCommands.ProcessCommand(this, command, data);
                break;

            case "VRFY":
                if (_protocolVersion == 0)
                {
                    WriteCode(503, "5.5.1", "EHLO/HELO first.");
                    return;
                }
                WriteCode(252, "5.5.1");
                break;

            default:
                if (_protocolVersion == 0)
                {
                    WriteCode(503, "5.5.1", "EHLO/HELO first.");
                    return;
                }
                WriteCode(502, "5.5.1");
                break;
            }
        }
Exemplo n.º 8
0
 public int Logout()
 {
     ExternalProvider.SignOut(Request, HttpContext.Current.User.Identity.AuthenticationType);
     return(AuthenticationCommands.SetTokenExpires());
 }
Exemplo n.º 9
0
        public static void AddUserToGroup(int userId, string groupName = "UnitTest Group")
        {
            var groupId = AuthenticationCommands.CreateSecurityGroup(groupName);

            AuthenticationCommands.AddUserToGroup(userId, groupId);
        }