public DialogResult VerifyConfigurationAsUser()

in wwauth/Google.Solutions.WWAuth/View/EditConfigurationViewModel.cs [80:147]


        public DialogResult VerifyConfigurationAsUser(
            IWin32Window owner)
        {
            //
            // Launch a copy of this process as a different user.
            //
            // By running the entire program as that user, we not
            // only test if authentication works, but also ensure
            // that the user is allowed to access any required
            // certificates, files, etc.
            //
            // Create a temporary copy since the last changes might not
            // have been applied yet.
            //
            var tempFile = this.file.Clone();
            tempFile.SaveAs(Path.GetTempFileName());

            var result = shellAdapter.PromptForCredentials(
                owner,
                out var credential);
            if (result == DialogResult.OK)
            {
                //
                // Grant the user access to the file.
                //
                // N.B. Passing the file contents on the command line
                // would save us from changing file permissions, but
                // CreateProcessWithLogon has a 1K command line limit,
                // which is too short for that purpose.
                //
                var access = File.GetAccessControl(tempFile.FilePath);
                access.AddAccessRule(new FileSystemAccessRule(
                    credential.UserName,
                    FileSystemRights.Read,
                    AccessControlType.Allow));
                File.SetAccessControl(tempFile.FilePath, access);

                //
                // Launch a new process as the selected user.
                //
                try
                {
                    shellAdapter.StartProcessAsUser(
                        Program.ExecutablePath,
                        new AttendedCommandLineOptions()
                        {
                            Executable = string.Empty,
                            Verify = tempFile.FilePath
                        }.ToString(),
                        credential);
                }
                catch (Win32Exception e) when (e.NativeErrorCode == NativeMethods.ERROR_DIRECTORY)
                {
                    throw new IOException(
                        $"The user {credential.UserName} does not have access to the " +
                        $"program file {Program.ExecutablePath}.\n\n" +
                        "Modify the file permissions or move the program file to a " +
                        "different folder to ensure that the user can access and run " +
                        "this program.");
                }

                return DialogResult.OK;
            }
            else
            {
                return result;
            }
        }