Initialize() public method

Initializes the UserInfo object.
Failed to initialize directory entry for .
public Initialize ( ) : void
return void
Beispiel #1
0
        /// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            UserInfo userInfo;
            WindowsImpersonationContext impersonationContext = null;
            ISecurityProvider provider;

            try
            {
                // Determine whether we need to try impersonating the user
                userInfo = new UserInfo(TextBoxUserName.Text);

                // If the application is unable to access the domain, possibly because the local user
                // running the application does not have access to domain objects, it's possible that
                // the user logging in does have access to the domain. So we attempt to impersonate the
                // user logging in to allow authentication to proceed
                if (!userInfo.DomainRespondsForUser && TryImpersonate(userInfo.LoginID, TextBoxPassword.Password, out impersonationContext))
                {
                    try
                    {
                        // Working around a known issue - DirectorySearcher will often throw
                        // an exception the first time it is used after impersonating another
                        // user so we get that out of the way here
                        userInfo.Initialize();
                    }
                    catch (InitializationException)
                    {
                        // Exception is expected so we ignore it
                    }
                }

                // Initialize the security provider
                provider = SecurityProviderUtility.CreateProvider(TextBoxUserName.Text);

                // Attempt to authenticate user
                if (provider.Authenticate(TextBoxPassword.Password))
                {
                    // Setup security provider for subsequent uses
                    SecurityProviderCache.CurrentProvider = provider;
                    ClearErrorMessage();
                    ExitSuccess = true;
                }
                else
                {
                    // Verify their password hasn't expired
                    if (provider.UserData.IsDefined && provider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // Display password expired message
                        DisplayErrorMessage(string.Format("Your password has expired. {0} You must change your password to continue.", provider.AuthenticationFailureReason));
                        m_displayType = DisplayType.ChangePassword;
                        ManageScreenVisualization();
                        TextBoxPassword.Password = "";
                    }
                    else
                    {
                        // Display login failure message
                        DisplayErrorMessage("The username or password is invalid. " + provider.AuthenticationFailureReason);

                        if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                            TextBoxUserName.Focus();
                        else
                            TextBoxPassword.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage("Login failed: " + ex.Message);

                if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                    TextBoxUserName.Focus();
                else
                    TextBoxPassword.Focus();
            }
            finally
            {
                if ((object)impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Handles service start event.
        /// </summary>
        /// <param name="args">Service start arguments.</param>
        public virtual void Start(string[] args)
        {
            string userInput = null;
            Arguments arguments = new Arguments(string.Join(" ", args));

            if (arguments.Exists("OrderedArg1") && arguments.Exists("restart"))
            {
                string serviceName = arguments["OrderedArg1"];

                if (Common.IsPosixEnvironment)
                {
                    string serviceCommand = FilePath.GetAbsolutePath(serviceName);

                    try
                    {
                        Command.Execute(serviceCommand, "stop");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to stop the {0} daemon: {1}\r\n", serviceName, ex.Message);
                    }

                    try
                    {
                        Command.Execute(serviceCommand, "start");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to restart the {0} daemon: {1}\r\n", serviceName, ex.Message);
                    }
                }
                else
                {
                    // Attempt to access service controller for the specified Windows service
                    ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase) == 0);

                    if (serviceController != null)
                    {
                        try
                        {
                            if (serviceController.Status == ServiceControllerStatus.Running)
                            {
                                WriteLine("Attempting to stop the {0} Windows service...", serviceName);

                                serviceController.Stop();

                                // Can't wait forever for service to stop, so we time-out after 20 seconds
                                serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D));

                                if (serviceController.Status == ServiceControllerStatus.Stopped)
                                    WriteLine("Successfully stopped the {0} Windows service.", serviceName);
                                else
                                    WriteLine("Failed to stop the {0} Windows service after trying for 20 seconds...", serviceName);

                                // Add an extra line for visual separation of service termination status
                                WriteLine("");
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Failed to stop the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                        }
                    }

                    // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances
                    try
                    {
                        Process[] instances = Process.GetProcessesByName(serviceName);

                        if (instances.Length > 0)
                        {
                            int total = 0;
                            WriteLine("Attempting to stop running instances of the {0}...", serviceName);

                            // Terminate all instances of service running on the local computer
                            foreach (Process process in instances)
                            {
                                process.Kill();
                                total++;
                            }

                            if (total > 0)
                                WriteLine("Stopped {0} {1} instance{2}.", total, serviceName, total > 1 ? "s" : "");

                            // Add an extra line for visual separation of process termination status
                            WriteLine("");
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to terminate running instances of the {0}: {1}\r\n", serviceName, ex.Message);
                    }

                    // Attempt to restart Windows service...
                    if (serviceController != null)
                    {
                        try
                        {
                            // Refresh state in case service process was forcibly stopped
                            serviceController.Refresh();

                            if (serviceController.Status != ServiceControllerStatus.Running)
                                serviceController.Start();
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Failed to restart the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                        }
                    }
                }
            }
            else
            {
                if (arguments.Exists("server"))
                {
                    // Override default settings with user provided input. 
                    m_clientHelper.PersistSettings = false;
                    m_remotingClient.PersistSettings = false;
                    m_remotingClient.ConnectionString = string.Format("Server={0}", arguments["server"]);
                }

                long lastConnectAttempt = 0;

                // Connect to service and send commands.
                while (!string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        // Do not reattempt connection too quickly
                        while (DateTime.UtcNow.Ticks - lastConnectAttempt < Ticks.PerSecond)
                            Thread.Sleep(200);

                        lastConnectAttempt = DateTime.UtcNow.Ticks;

                        if (!m_authenticationFailure)
                        {
                            // If there has been no authentication
                            // failure, connect normally
                            Connect();
                        }
                        else
                        {
                            UserInfo userInfo;
                            StringBuilder username = new StringBuilder();
                            StringBuilder password = new StringBuilder();

                            // If there has been an authentication failure,
                            // prompt the user for new credentials
                            PromptForCredentials(username, password);

                            try
                            {
                                // Attempt to set network credentials used when attempting AD authentication
                                userInfo = new UserInfo(username.ToString());
                                userInfo.Initialize();
                                SetNetworkCredential(new NetworkCredential(userInfo.LoginID, password.ToString()));
                            }
                            catch
                            {
                                // Even if this fails, we can still pass along user credentials
                            }

                            Connect(username.ToString(), password.ToString());
                        }

                        while (m_authenticated && m_clientHelper.Enabled && !string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
                        {
                            // Wait for a command from the user. 
                            userInput = System.Console.ReadLine();

                            // Write a blank line to the console.
                            WriteLine();

                            if (!string.IsNullOrWhiteSpace(userInput))
                            {
                                // The user typed in a command and didn't just hit <ENTER>. 
                                switch (userInput.ToUpper())
                                {
                                    case "CLS":
                                        // User wants to clear the console window. 
                                        System.Console.Clear();
                                        break;

                                    case "EXIT":
                                        // User wants to exit the telnet session with the service. 
                                        if (m_telnetActive)
                                        {
                                            userInput = string.Empty;
                                            m_clientHelper.SendRequest("Telnet -disconnect");
                                        }

                                        break;

                                    case "LOGIN":
                                        m_authenticated = false;
                                        m_authenticationFailure = true;
                                        break;

                                    default:
                                        // User wants to send a request to the service. 
                                        m_clientHelper.SendRequest(userInput);

                                        if (string.Compare(userInput, "Help", StringComparison.OrdinalIgnoreCase) == 0)
                                            DisplayHelp();

                                        break;
                                }
                            }
                        }

                        m_clientHelper.Disconnect();
                    }
                    catch (Exception)
                    {
                        // Errors during the outer connection loop
                        // should simply force an attempt to reconnect
                        m_clientHelper.Disconnect();
                    }
                }
            }
        }
Beispiel #3
0
        private static void PrincipalRefreshTimer_Elapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            UserInfo userInfo;
            ISecurityProvider provider;
            WindowsImpersonationContext impersonationContext;

            if ((object)s_currentPrincipal != null)
            {
                // If user is no longer authenticated, provider session may have expired so provider session will
                // now be reinitialized. This step will "re-validate" user's current state (e.g., locked-out).
                if (!SecurityProviderCache.TryGetCachedProvider(s_currentPrincipal.Identity.Name, out provider))
                {
                    impersonationContext = null;

                    try
                    {
                        // Determine whether we need to try impersonating the user
                        userInfo = new UserInfo(CurrentUser);

                        // If the application is unable to access the domain, possibly because the local user
                        // running the application does not have access to domain objects, it's possible that
                        // the user logging in does have access to the domain. So we attempt to impersonate the
                        // user logging in to allow authentication to proceed
                        if (!userInfo.DomainRespondsForUser && TryImpersonate(userInfo.LoginID, GetCurrentUserPassword(), out impersonationContext))
                        {
                            try
                            {
                                // Working around a known issue - DirectorySearcher will often throw
                                // an exception the first time it is used after impersonating another
                                // user so we get that out of the way here
                                userInfo.Initialize();
                            }
                            catch (InitializationException)
                            {
                                // Exception is expected so we ignore it
                            }
                        }

                        Thread.CurrentPrincipal = s_currentPrincipal;
                        SecurityProviderCache.ReauthenticateCurrentPrincipal();
                        CurrentPrincipal = Thread.CurrentPrincipal as SecurityPrincipal;
                    }
                    finally
                    {
                        if ((object)impersonationContext != null)
                        {
                            impersonationContext.Undo();
                            impersonationContext.Dispose();
                        }
                    }

                    // Rights may have changed -- notify for revalidation of menu commands
                    Application.Current.Dispatcher.BeginInvoke(new Action(OnCurrentPrincipalRefreshed));
                }
            }

            s_principalRefreshTimer.Start();
        }