本文整理汇总了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;
}
}
示例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;
}
}
示例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".
}
示例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;
}
示例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());
}
}
示例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;
}
}
示例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);
}
示例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;
}
示例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;
}
示例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";
}
示例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;
}
示例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
}
示例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);
}
示例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
}
}
}
示例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());
}
}