views:

1470

answers:

3

Is there a canonical way to test to see if a user has administrative privileges on a machine?

I'm going to be starting a long running process, and much later in the process' lifetime it's going to attempt some things that require admin privileges.

I'd like to be able to test up front if the user has those rights rather than later on.

+7  A: 

This will check if user is in the local Administrators group (assuming you're not checking for domain admin permissions)

using System.Security.Principal;

public bool IsUserAdministrator()
{
    //bool value to hold our return value
    bool isAdmin;
    try
    {
        //get the currently logged in user
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}
Wadih M.
This will determine if the user is in the BUILTIN\Administrators group, but will it show if the user is elevated on Vista?
John Saunders
Is catching every exception really necessary?
Jakub Šturc
If anyone can test this on Vista, it would be great.
Wadih M.
necessary no, but sure saves you the trouble down the road of having runtime errors if something odd happens
Jared
@Jared: it also hides any serious errors that may happen in that block. It should be removed.
John Saunders
This won't work in Vista if UAC is enabled. The reason is that UAC creates a "split token" for users with admin priveleges and the "split token" explicitly excludes all admin roles (including things like "Domain Admin").
Jacob Proffitt
I tested this on Windows Server 2008 with UAC enabled. It works like this: elevated administrator -> true, non-elevated administrator -> false, standard user -> false
Joe Daley
+1  A: 

Use can use WMI with something like this to find out if the account is an admin, and just about anything else you want to know about there account

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher = 
                    new ManagementObjectSearcher("root\\CIMV2", 
                    "SELECT * FROM Win32_UserAccount"); 

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_UserAccount instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("AccountType: {0}", queryObj["AccountType"]);
                    Console.WriteLine("FullName: {0}", queryObj["FullName"]);
                    Console.WriteLine("Name: {0}", queryObj["Name"]);
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

To make it easier to get started download WMI Creator

you can also use this it access active directory (LDAP) or anything else on you computer/network

Bob The Janitor
+5  A: 

If you want to make sure your solution works in Vista UAC, and have .Net Framework 3.5 or better, you might want to use the System.DirectoryServices.AccountManagement namespace. Your code would look something like:

bool isAllowed = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, null))
{
    UserPrincipal up = UserPrincipal.Current;
    GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, "Administrators");
    if (up.IsMemberOf(gp))
        isAllowed = true;
}
Jacob Proffitt
will it show if the user is elevated on Vista?
Keivan
It *should*. I haven't tested it against the builtin.Administrators account. My application was testing against a domain. http://theruntime.com/blogs/jacob/archive/2009/02/13/so-you-think-youre-an-admin.aspx
Jacob Proffitt
PLEASE Dont hardcode Administrators (pretty sure this is the localisable string, not BUILTIN\ADministrators well known string)
Ruben Bartelink
So what would you use, Ruben?
Jacob Proffitt