当前位置: 首页>>代码示例>>C#>>正文


C# WindowsPrincipal.IsInRole方法代码示例

本文整理汇总了C#中System.Security.Principal.WindowsPrincipal.IsInRole方法的典型用法代码示例。如果您正苦于以下问题:C# WindowsPrincipal.IsInRole方法的具体用法?C# WindowsPrincipal.IsInRole怎么用?C# WindowsPrincipal.IsInRole使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Principal.WindowsPrincipal的用法示例。


在下文中一共展示了WindowsPrincipal.IsInRole方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Form1

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

            //Create a windowsidentity object representing the current user
            WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

            //Create a windowsprincipal object representing the current user
            WindowsPrincipal currentprincipal = new WindowsPrincipal(currentIdentity);

            //Set the security policy context to windows security
            System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            //hide the subtract and multiply button if user is not and Administrator
            if(!currentprincipal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                subtractButton.Visible = false;
                multiplyButton.Visible = false;
            }

            //hide the add button if user is not in Users group
            if(!currentprincipal.IsInRole(WindowsBuiltInRole.User))
            {
                addButton.Visible = false;
            }

            //Hide the Divide button if the user is not named CPhilips
            if(!(currentIdentity.Name.ToLower() == Environment.MachineName.ToLower() + @"\rafa&pri"))
            {
                divideButton.Visible = false;
            }
		}
开发者ID:Rafael-Miceli,项目名称:ProjectStudiesCert70-536,代码行数:35,代码来源:Form1.cs

示例2: HaveFolderPermissions

        /// <summary>Checks if the current process has the necessary permissions to a folder. This allows "custom" elevation of limited users -- allowing them control over normally restricted folders.</summary>
        /// <param name="folder">The full path to the folder to check.</param>
        /// <returns>True if the user has permission, false if not.</returns>
        static bool HaveFolderPermissions(string folder)
        {
            try
            {
                const FileSystemRights RightsNeeded = FileSystemRights.Traverse |
                                                      FileSystemRights.DeleteSubdirectoriesAndFiles |
                                                      FileSystemRights.ListDirectory | FileSystemRights.CreateFiles |
                                                      FileSystemRights.CreateDirectories |
                                                      FileSystemRights.Modify; //Read, ExecuteFile, Write, Delete

                FileSystemSecurity security = Directory.GetAccessControl(folder);

                var rules = security.GetAccessRules(true, true, typeof(NTAccount));

                var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent());

                FileSystemRights RightsHave = 0;
                FileSystemRights RightsDontHave = 0;

                foreach (FileSystemAccessRule rule in rules)
                {
                    // First check to see if the current user is even in the role, if not, skip
                    if (rule.IdentityReference.Value.StartsWith("S-1-"))
                    {
                        var sid = new SecurityIdentifier(rule.IdentityReference.Value);
                        if (!currentuser.IsInRole(sid))
                            continue;
                    }
                    else
                    {
                        if (!currentuser.IsInRole(rule.IdentityReference.Value))
                            continue;
                    }

                    if (rule.AccessControlType == AccessControlType.Deny)
                        RightsDontHave |= rule.FileSystemRights;
                    else
                        RightsHave |= rule.FileSystemRights;
                }

                // exclude "RightsDontHave"
                RightsHave &= ~RightsDontHave;

                //Note: We're "XOR"ing with RightsNeeded to eliminate permissions that
                //      "RightsHave" and "RightsNeeded" have in common. Then we're
                //      ANDing that result with RightsNeeded to get permissions in
                //      "RightsNeeded" that are missing from "RightsHave". The result
                //      should be 0 if the user has RightsNeeded over the folder (even
                //      if "RightsHave" has flags that aren't present in the
                //      "RightsNeeded" -- which can happen because "RightsNeeded" isn't
                //      *every* possible flag).

                // Check if the user has full control over the folder.
                return ((RightsHave ^ RightsNeeded) & RightsNeeded) == 0;
            }
            catch
            {
                return false;
            }
        }
开发者ID:chances,项目名称:Animatum,代码行数:63,代码来源:MainForm.UserElevation.cs

示例3: Execute

        public void Execute()
        {
            PrintHeader();

            var id = WindowsIdentity.GetCurrent();
            Console.WriteLine("Identity Id: " + id.Name);

            var account = new NTAccount(id.Name);
            var sid = account.Translate(typeof(SecurityIdentifier));
            Console.WriteLine("SecurityIdentifier (sid): " + sid.Value);

            foreach (var group in id.Groups.Translate(typeof(NTAccount)))
                Console.WriteLine("InGroup: " + group);

            var principal = new WindowsPrincipal(id);
            var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins));

            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
            Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins));
            Console.WriteLine();

            // be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights,
            // unless the process was run elevated "as Admin".
        }
开发者ID:stevenh77,项目名称:ClaimsBasedSecurityDemo,代码行数:25,代码来源:WindowsIdentityExample.cs

示例4: Form1

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

            WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

            WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);

            System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            if (!currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                subtractButton.Visible = false;
                multiplyButton.Visible = false;
            }
            
            if (!currentPrincipal.IsInRole(WindowsBuiltInRole.User))
                addButton.Visible = false;

            if (!(currentIdentity.Name.ToLower() == System.Environment.MachineName.ToLower() + @"\donal"))
                divideButton.Visible = false;
		}
开发者ID:oblivious,项目名称:Oblivious,代码行数:25,代码来源:Form1.cs

示例5: Main

        static void Main(string[] args)
        {
            try
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

                Console.WriteLine("Getting current principal");
                IPrincipal myPrincipal = Thread.CurrentPrincipal;

                Console.WriteLine("Name: " + myPrincipal.Identity.Name);
                Console.WriteLine("AuthenicationsType: " + myPrincipal.Identity.AuthenticationType);
                Console.WriteLine("IsAuthenticated: " + myPrincipal.Identity.IsAuthenticated);

                Console.WriteLine("\nNow setting principal policy on the app domain to windows.");
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                Console.WriteLine("CurrentPrincipal Type: " + Thread.CurrentPrincipal.GetType());
                Console.WriteLine("CurrentPrincipal Name: " + Thread.CurrentPrincipal.Identity.Name);

                WindowsPrincipal newPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;

                Console.WriteLine("Name: " + newPrincipal.Identity.Name);
                Console.WriteLine("AuthenicationsType: " + newPrincipal.Identity.AuthenticationType);
                Console.WriteLine("IsAuthenticated: " + newPrincipal.Identity.IsAuthenticated + "\n\n");

                WindowsIdentity myIdent = WindowsIdentity.GetCurrent();
                Console.WriteLine("Name: " + myIdent.Name);
                Console.WriteLine("AuthenicationsType: " + myIdent.AuthenticationType);
                Console.WriteLine("IsAuthenticated: " + myIdent.IsAuthenticated);

                WindowsPrincipal principal = new WindowsPrincipal(myIdent);

                if (principal.IsInRole(@"BUILTIN\Administrators"))
                {
                    Console.WriteLine("You are an administrator");
                }
                else
                {
                    Console.WriteLine("You are not an administrator");
                }

                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine("You are an administrator");
                }
                else
                {
                    Console.WriteLine("You are not an administrator");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
开发者ID:oblivious,项目名称:Oblivious,代码行数:54,代码来源:Program.cs

示例6: HasDeletePermission

        private static bool HasDeletePermission(string FilePath)
        {
            try
            {
                FileSystemSecurity security;
                if (File.Exists(FilePath))
                {
                    security = File.GetAccessControl(FilePath);
                }
                else
                {
                    security = Directory.GetAccessControl(Path.GetDirectoryName(FilePath));
                }
                var rules = security.GetAccessRules(true, true, typeof(NTAccount));

                var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                bool result = false;
                foreach (FileSystemAccessRule rule in rules)
                {
                    if (0 == (rule.FileSystemRights &
                        (FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles)))
                    {
                        continue;
                    }

                    if (rule.IdentityReference.Value.StartsWith("S-1-"))
                    {
                        var sid = new SecurityIdentifier(rule.IdentityReference.Value);
                        if (!currentuser.IsInRole(sid))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!currentuser.IsInRole(rule.IdentityReference.Value))
                        {
                            continue;
                        }
                    }

                    if (rule.AccessControlType == AccessControlType.Deny)
                        return false;
                    if (rule.AccessControlType == AccessControlType.Allow)
                        result = true;
                }
                return result;
            }
            catch
            {
                return false;
            }
        }
开发者ID:XPGDaniel,项目名称:PermissionScanner,代码行数:53,代码来源:Program.cs

示例7: GetHasElevatedPrivileges

        public static bool GetHasElevatedPrivileges()
        {
            if (!IsWindows8()) return true;

            var identity = WindowsIdentity.GetCurrent();

            if (identity == null)
                return false;

            var principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200);
        }
开发者ID:olivierdagenais,项目名称:GoToWindow,代码行数:12,代码来源:WindowsRuntimeHelper.cs

示例8: calculateUserGroupBasedOnWindowsIdentity

		public UserGroup calculateUserGroupBasedOnWindowsIdentity()
		{
			var identity = WindowsIdentity.GetCurrent();
			var principal = new WindowsPrincipal(identity);
			if (principal.IsInRole(adminGroup))
				return UserGroup.Admin;
			if (principal.IsInRole(editorGroup))
				return UserGroup.Editor;
			if (principal.IsInRole(readerGroup))
				return UserGroup.Reader;
			return UserGroup.None;
		}
开发者ID:TeamMentor,项目名称:TM_3.2_with_OWASP_Library,代码行数:12,代码来源:WindowsAuthentication.cs

示例9: ShowPrincipal

 public static WindowsPrincipal ShowPrincipal(WindowsIdentity identity)
 {
     WriteLine("Show principal information");
     WindowsPrincipal principal = new WindowsPrincipal(identity);
     if (principal == null)
     {
         WriteLine("not a Windows Principal");
         return null;
     }
     WriteLine($"Users? {principal.IsInRole(WindowsBuiltInRole.User)}");
     WriteLine($"Administrators? {principal.IsInRole(WindowsBuiltInRole.Administrator)}");
     WriteLine();
     return principal;
 }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:14,代码来源:Program.cs

示例10: GetAccountType

        //권한
        public static string GetAccountType()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                return "Admin";
            else if (principal.IsInRole(WindowsBuiltInRole.User))
                return "User";
            else if (principal.IsInRole(WindowsBuiltInRole.Guest))
                return "Guest";
            else
                return "Unknown";
        }
开发者ID:kr-app-a72,项目名称:Computer-Info,代码行数:15,代码来源:Main.cs

示例11: calculateUserGroupBasedOnWindowsIdentity

 public UserGroup calculateUserGroupBasedOnWindowsIdentity(WindowsIdentity identity)
 {
     if (identity != null)
     {
         var windowsAuth = TMConfig.Current.WindowsAuthentication;
         var principal = new WindowsPrincipal(identity);
         if (principal.IsInRole(windowsAuth.AdminGroup.trim()))
             return UserGroup.Admin;
         if (principal.IsInRole(windowsAuth.EditorGroup.trim()))
             return UserGroup.Editor;
         if (principal.IsInRole(windowsAuth.ReaderGroup.trim()))
             return UserGroup.Reader;
     }
     return UserGroup.None;
 }
开发者ID:TeamMentor,项目名称:Dev,代码行数:15,代码来源:WindowsAuthentication.cs

示例12: Install

        /// <summary>
        /// This routine should be called automatically by the MSI during setup, but it can also be called using:
        ///     "installutil.exe Archiver.dll"
        /// </summary>
        /// <param name="savedState">State dictionary passed in by the installer code</param>
        public override void Install (IDictionary savedState)
        {
            #region Check to make sure we're in an Administrator role
            WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            if (wp.IsInRole(WindowsBuiltInRole.Administrator) == false)
            {
                MessageBox.Show("You must be an Administrator to install Rtp or run it for the first time.", "Administrator Privileges Required", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Application.Exit();
            }
            #endregion

            #region Uninstall in case we weren't uninstalled cleanly before
            IDictionary state = new Hashtable();
            Uninstall(state);
            if (state.Count != 0)
                Commit(state);
            state = null;
            #endregion

            #region Call base.Install
            base.Install(savedState);
            #endregion

            #region Install the Event Logs
            ArchiveServiceEventLog.Install();
            #endregion
            
            #region Create PerfCounters
            PCInstaller.Install();
            #endregion

            #region Save the fact that we're installed to the registry
            Installed = true;
            #endregion
        }
开发者ID:abhishek-kumar,项目名称:AIGA,代码行数:40,代码来源:Installer.cs

示例13: isAdministrator

 private static bool isAdministrator()
 {
     SimpleLogger.Instance().WriteLine("Checking privileges...");
     WindowsIdentity identity = WindowsIdentity.GetCurrent();
     WindowsPrincipal principal = new WindowsPrincipal(identity);
     return principal.IsInRole(WindowsBuiltInRole.Administrator);
 }
开发者ID:DamienGarrido,项目名称:MAudioDriverMonitor,代码行数:7,代码来源:Program.cs

示例14: CheckUAC

        private void CheckUAC()
        {
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            if (!pricipal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                buttonInstallFiles.Enabled = false;
                buttonUninstallFiles.Enabled = false;
                buttonInstallFolders.Enabled = false;
                buttonUninstallFolders.Enabled = false;

                MessageBox.Show("UAC is preventing this action to complete. Restarting as administrator.");
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.Verb = "runas";
                processInfo.FileName = Application.ExecutablePath;
                try
                {
                    Process.Start(processInfo);
                    Application.Exit();
                }
                catch (Win32Exception)
                {
                    //Do nothing. Probably the user canceled the UAC window
                }
            }
        }
开发者ID:smatsson,项目名称:UnpackQueue,代码行数:25,代码来源:InstallerForm.cs

示例15: Main

        static void Main()
        {
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);

            if (hasAdministrativeRight == false)
            {
                ProcessStartInfo processInfo = new ProcessStartInfo(); //создаем новый процесс
                processInfo.Verb = "runas";
                //в данном случае указываем, что процесс должен быть запущен с правами администратора
                processInfo.FileName = Application.ExecutablePath; //указываем исполняемый файл (программу) для запуска
                try
                {
                    Process.Start(processInfo); //пытаемся запустить процесс
                }
                catch (Win32Exception)
                {
                    //Ничего не делаем, потому что пользователь, возможно, нажал кнопку "Нет" в ответ на вопрос о запуске программы в окне предупреждения UAC (для Windows 7)
                }
                Application.Exit();
                //закрываем текущую копию программы (в любом случае, даже если пользователь отменил запуск с правами администратора в окне UAC)
            }
            else //имеем права администратора, значит, стартуем
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
        }
开发者ID:sw0rl0k,项目名称:selfcontrolapp,代码行数:29,代码来源:Program.cs


注:本文中的System.Security.Principal.WindowsPrincipal.IsInRole方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。