tags:

views:

211

answers:

3

How do I detect if an arbitrary user is an administrator on a machine? I have the user's domain and username but not password. The user is NOT the currently logged in user, so I can't just use WindowsIdentity.GetCurrent.

+1  A: 

Use LDAP. See examples here.

Otávio Décio
Perfect, thanks.
Jonathan Allen
A: 

You can use System.DirectoryServices to first load the local machine and then search for any users within a given group. Try out the following code:

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators","group");
object members = admGroup.Invoke("members", null);

Then create a new DirectoryEntry for each member in the members object:

foreach (object groupMember in (IEnumerable)members)
{
  DirectoryEntry member = new DirectoryEntry(groupMember);
  //Do what you want
}

The member object inside of that foreach loop is has a load of data about the user inside it. Compare your member's name with the current one in the loop:

if (memberSearch.name == member.name) {
  return true;
} else {
  return false;
}

You could also search through the members object to find the user etc. There are plenty of ways of doing it. Hope this helps!

Jamie Rumbelow
+2  A: 

Using UserPrincipal.GetAuthorizationGroups to check if the user is in a group that is allowed administrative access to the machine.

First get a UserPrincipal object using FindByIdentity. Then get the authorization groups that the user is a member of. Check each group to see if matches the builtin administrators group. If the builtin administrators group is not in the user's authorization groups, then the user is not an administrator on the local machine.

using System.DirectoryServices.AccountManagement;
using System.Linq;

var name = Environment.UserName;
var user = UserPrincipal.FindByIdentity( new PrincipalContext( ContextType.Domain ), name );
var groups = user.GetAuthorizationGroups();
var isAdmin = groups.Any( g => g.Name == "Administrators" );    
Console.WriteLine( "Admin: " + isAdmin );
tvanfosson