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


C# Principal.WindowsPrincipal类代码示例

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


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

示例1: BeforeInvoke

        public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, System.ServiceModel.Channels.Message message)
        {
            WindowsPrincipal currentlyPrincipal = null;
            if (ServiceSecurityContext.Current != null && ServiceSecurityContext.Current.WindowsIdentity != null)
            {
                currentlyPrincipal = new WindowsPrincipal(ServiceSecurityContext.Current.WindowsIdentity);
            }

            string action = OperationContext.Current.IncomingMessageHeaders.Action;
            if (!string.IsNullOrEmpty(action))
            {
                var actions = action.Split('/');
                string methodName = actions[actions.Length - 1];
                string serviceName = actions[actions.Length - 2];

                if (!this.authorizationCheckStrategy.IsAuthorized(serviceName, methodName, currentlyPrincipal))
                {
                    var logMessage = new StringBuilder();
                    var endpointMsg = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                    logMessage.Append("Access Denied");
                    logMessage.AppendFormat("Service: {0}, Method:{1}", serviceName, methodName).AppendLine();
                    logMessage.AppendFormat("Client IP: {0}:{1}", endpointMsg.Address, endpointMsg.Port).AppendLine();
                    logMessage.AppendFormat("Currently Principal: {0}", currentlyPrincipal.Identity.Name).AppendLine();
                    var accessDeniedException = new SecurityAccessDeniedException();
                    _logger.LogWarning(logMessage.ToString());
                    throw accessDeniedException;
                }
            }

            var ticket = Guid.NewGuid();
            _logger.Debug(string.Format("{0} BeforeInvoke {1}, Method {2}", DateTime.Now, ticket, message.Headers.Action));
            return ticket;
        }
开发者ID:philfanzhou,项目名称:PredictFuture,代码行数:33,代码来源:SecurityCallContextInitializer.cs

示例2: calculateUserGroupBasedOnWindowsIdentity

        public void calculateUserGroupBasedOnWindowsIdentity()
        {
            Action<UserGroup> testMappings = (expectedUserGroup)=>
                {
                    var identity  = WindowsIdentity.GetCurrent();            
                    Assert.NotNull(identity);

                    var principal = new WindowsPrincipal(identity);
                    Assert.NotNull(principal);

                    Assert.AreEqual(identity.AuthenticationType, "NTLM");
                    var defaultUserGroup = windowsAuthentication.calculateUserGroupBasedOnWindowsIdentity(identity);
                    Assert.AreEqual(expectedUserGroup, defaultUserGroup);   
                };
         
            testMappings(UserGroup.None);
            
            //create a copy of the current values before changing them in the test below
            var tmConfig_ReaderGroup = tmConfig.WindowsAuthentication.ReaderGroup;
            var tmConfig_EditorGroup = tmConfig.WindowsAuthentication.EditorGroup;
            var tmConfig_AdminGroup  = tmConfig.WindowsAuthentication.AdminGroup;


            tmConfig.WindowsAuthentication.ReaderGroup = "Users";
            testMappings(UserGroup.Reader);
            tmConfig.WindowsAuthentication.ReaderGroup = tmConfig_ReaderGroup;
            
            tmConfig.WindowsAuthentication.EditorGroup = "Users";
            testMappings(UserGroup.Editor);
            tmConfig.WindowsAuthentication.EditorGroup = tmConfig_EditorGroup;
            
            tmConfig.WindowsAuthentication.AdminGroup =  "Users";
            testMappings(UserGroup.Admin);
            tmConfig.WindowsAuthentication.AdminGroup = tmConfig_AdminGroup;
        }
开发者ID:TeamMentor,项目名称:Dev,代码行数:35,代码来源:Test_WindowsAuthentication.cs

示例3: CheckAdministrator

        /// <summary>
        /// 检查是否是管理员身份
        /// </summary>
        private void CheckAdministrator()
        {
            var wi = WindowsIdentity.GetCurrent();
            var wp = new WindowsPrincipal(wi);

            bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);

            if (!runAsAdmin)
            {
                // It is not possible to launch a ClickOnce app as administrator directly,
                // so instead we launch the app as administrator in a new process.
                var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);

                // The following properties run the new process as administrator
                processInfo.UseShellExecute = true;
                processInfo.Verb = "runas";

                // Start the new process
                try
                {
                    Process.Start(processInfo);
                }
                catch
                {
                    MessageBox.Show("没有管理员权限\n请右键该程序之后点击“以管理员权限运行”");
                }

                // Shut down the current process
                Environment.Exit(0);
            }
        }
开发者ID:AldarisX,项目名称:Sakuya-Aki,代码行数:34,代码来源:App.xaml.cs

示例4: 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

示例5: CheckUserRights

            public static bool CheckUserRights(string userLogin, string rightName)
            {
                string programName = WebConfigurationManager.AppSettings["progName"];
                bool flag = false;

                SqlParameter pProgramName = new SqlParameter() { ParameterName = "program_name", Value = programName, DbType = DbType.AnsiString };
                SqlParameter pRightName = new SqlParameter() { ParameterName = "sys_name", Value = rightName, DbType = DbType.AnsiString };

                DataTable dt = new DataTable();

                dt = ExecuteQueryStoredProcedure(sp, "getUserGroupSid", pProgramName, pRightName);

                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];

                    string sid = dr["sid"].ToString();

                    try
                    {
                        WindowsIdentity wi = new WindowsIdentity(userLogin);
                        WindowsPrincipal wp = new WindowsPrincipal(wi);
                        SecurityIdentifier grpSid = new SecurityIdentifier(sid);

                        flag = wp.IsInRole(grpSid);
                    }
                    catch (Exception ex)
                    {
                        flag = false;
                    }
                }

                return flag;
            }
开发者ID:WakeDown,项目名称:ServicePlaning,代码行数:34,代码来源:Db.Users.cs

示例6: IsUserAdministrator

 public static bool IsUserAdministrator()
 {
     bool isAdmin;
     WindowsIdentity user = null;
     try
     {
         //get the currently logged in user
         user = WindowsIdentity.GetCurrent();
         WindowsPrincipal principal = new WindowsPrincipal(user);
         isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
     }
     catch (UnauthorizedAccessException)
     {
         isAdmin = false;
     }
     catch (Exception)
     {
         isAdmin = false;
     }
     finally
     {
         if (user != null)
             user.Dispose();
     }
     return isAdmin;
 }
开发者ID:freshprogrammer,项目名称:FreshTools,代码行数:26,代码来源:FreshArchives.cs

示例7: 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

示例8: 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

示例9: IsAdministrator

        public static bool IsAdministrator()
        {
            var winId = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(winId);

            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
开发者ID:gitter-badger,项目名称:letsencrypt-win,代码行数:7,代码来源:IisSitePathProvider.cs

示例10: Interface

		public void Interface () 
		{
			WindowsPrincipal wp = new WindowsPrincipal (WindowsIdentity.GetAnonymous ());

			IPrincipal p = (wp as IPrincipal);
			AssertNotNull ("IPrincipal", p);
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:7,代码来源:WindowsPrincipalTest.cs

示例11: 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

示例12: IsAuthorized

        public bool IsAuthorized(string service, string method, WindowsPrincipal principal)
        {
            if (WebOperationContext.Current == null)
            {
                return true;
            }
            else
            {
                var methodInfo = CurrentEndpoint.Contract.ContractType.GetMethod(method);
                var attrs = methodInfo.GetCustomAttributes(typeof(TokenRequiredAttribute), false);
                if (attrs == null || attrs.Length == 0)
                {
                    return true;
                }
                else
                {
                    string token = WebOperationContext.Current.IncomingRequest.Headers.Get("Authorization-OAuth2");

                    if (string.IsNullOrEmpty(token))
                    {
                        return false;
                    }
                    else
                    {
                        return oauth2.VerifyAccessToken(token);
                    }
                }
            }
        }
开发者ID:philfanzhou,项目名称:PredictFuture,代码行数:29,代码来源:AuthorizationCheckStrategy.cs

示例13: ConsoleHostRawUserInterface

        ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base()
        {
            defaultForeground = ForegroundColor;
            defaultBackground = BackgroundColor;
            parent = mshConsole;
            // cacheKeyEvent is a value type and initialized automatically

            // add "Administrator: " prefix into the window title, but don't wait for it to finish
            //   (we may load resources which can take some time)
            Task.Run(() =>
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    string prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix;

                    // check using Regex if the window already has Administrator: prefix
                    // (i.e. from the parent console process)
                    string titlePattern = ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate;
                    titlePattern = Regex.Escape(titlePattern)
                        .Replace(@"\{1}", ".*")
                        .Replace(@"\{0}", Regex.Escape(prefix));
                    if (!Regex.IsMatch(this.WindowTitle, titlePattern))
                    {
                        this.WindowTitle = StringUtil.Format(ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate,
                            prefix,
                            this.WindowTitle);
                    }
                }
            });
        }
开发者ID:40a,项目名称:PowerShell,代码行数:32,代码来源:ConsoleHostRawUserInterface.cs

示例14: HaveAdminRights

        private bool HaveAdminRights()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
开发者ID:CoreyN,项目名称:PathEditor,代码行数:7,代码来源:App.xaml.cs

示例15: mainForm_Load

        private void mainForm_Load(object sender, EventArgs e)
        {
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
            if (!hasAdministrativeRight)
            {
                // relaunch the application with admin rights
                string fileName = Assembly.GetExecutingAssembly().Location;
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.Verb = "runas";
                processInfo.FileName = fileName;

                try
                {
                    Process.Start(processInfo);
                }
                catch (Win32Exception)
                {
                    this.Close();
                }

                return;
            }

            this.BringToFront();
            updateStats();
        }
开发者ID:GGG-KILLER,项目名称:SQL-Server-Controller,代码行数:27,代码来源:Form1.cs


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