I know there are several discussions about this subject but none really answer my exact question. I'm looking for a method that will check Remotely if a current logged on user has Admin rights. Whether he's a member of the local built in "administrators" group of the machine or member of a nested group inside "Administrators", such as "Domain Admins" for example. I found couple of methods but each provides only half solution.
Method #1 (work remotely but only checks the local "Administrators" Group):
private bool isAdmin()
{
ArrayList mem2 = new ArrayList();
string hostName = basicinfomodel.Loggedusername; //a username I get from another class
try
{
using (DirectoryEntry machine = new DirectoryEntry("WinNT://" + mycomputer.myComputerName)) // remote computer that I get from another class
{
//get local admin group
using (DirectoryEntry group = machine.Children.Find("Administrators", "Group"))
{
//get all members of local admin group
object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
//get account name
string accountName = new DirectoryEntry(member).Name;
mem2.Add(new DirectoryEntry(member).Name);
}
}
}
}
catch (Exception ex)
{
// catch
}
if (mem2.Contains(hostName.ToUpper()) || mem2.Contains(hostName.ToLower()))
return true;
else
return false;
}
Method #2 (check both local and domain admin privileges but not working remotely)
static bool isAdmin()
{
WindowsIdentity User = new WindowsIdentity(@"user01");
WindowsPrincipal princ = new WindowsPrincipal(User);
return princ.IsInRole(WindowsBuiltInRole.Administrator);
}
so as I said, I did not find any Method that will answer both needs.
thanks for the help!
Well, I think I found a way to do that, I'm sharing in case other people would want to use it. I played with couple of methods I found and created the following (seems to be working)
static bool isAdmin(string username, string machinename)
{
using (PrincipalContext ctxMacine = new PrincipalContext(ContextType.Machine, machinename))
{
using (PrincipalContext ctxDomain = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(ctxDomain, IdentityType.SamAccountName, username);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctxMacine, "Administrators");
foreach (UserPrincipal usr in gp.GetMembers(true))
{
if (up != null)
{
if (up.SamAccountName.ToUpper() == usr.SamAccountName.ToUpper())
{
return true;
}
}
}
}
}
return false;
}
Note
This is a naive implementation, you should validate your code, checking for null
's and handle exceptions.