Valleriani Valleriani - 3 months ago 15 Question

.NET - Issue trying to figure out if user is running ADMIN or not

I am trying to figure out how to determine if a program is running admin mode. I have shown some example coding on what I am using below in .NET:

Imports System.Security.Principal

Module Module1

Sub Main()

Dim id = WindowsIdentity.GetCurrent()
Dim pr = New WindowsPrincipal(id)
Dim isAdm As Boolean = pr.IsInRole(WindowsBuiltInRole.Administrator)

If isAdm = True Then
MessageBox.Show(Me, "Running Admin")
MessageBox.Show(Me, "Not Running Admin")
End If

End Sub

End Module

This works great for the most case but I have a user who is running Windows 7 Professional and it is returning TRUE no matter what if he ran as admin or not.

I don't know what would cause this, but is there a way to figure out why this is happening, and possibly a solution. Either to figure out that the program will always return true regardless through coding, or maybe a solution to the coding for this issue.

Any clues?


I don't know the .NET way; but i can give you the native code, which you can then P/Invoke call into:

    This function returns true if you are currently running with admin privileges.
    In Vista and later, if you are non-elevated, this function will 
    return false (you are not running with administrative privileges).
    If you *are* running elevated, then IsUserAdmin will return true, 
    as you are running with admin privileges.

    Windows provides this similar function in Shell32.IsUserAnAdmin. 
    But that function is depricated. 
    This code is adapted from from the docs for CheckTokenMembership:

       - you can be an administrator and not have admin privileges 
         (function returns false)
       - you can have admin privileges even though you're not an administrator 
         (function returns true)

    Any code released into the public domain. No attribution required.

Boolean IsUserAdmin()
   Boolean isAdmin;

   PSID administratorsGroup = StringToSid("S-1-5-32-544"); //well-known sid

   if (!CheckTokenMembership(0, administratorsGroup, out isAdmin)
      isAdmin = false;


   return isAdmin;

Note: Using CheckTokenMembership against the admins group is very different than other code floating around out there. The other code:

  • uses OpenProcessToken to get the "me" token
  • uses GetTokenInformation and TokenGroups to get TOKEN_GROUPS, which lists all groups the user is a member of
  • iterates the returned groups, using EqualSid to compare them with the Adminstrators SID

This is wrong because:

You can be a member of the administrators group, but not have administrator privelages!

This code can be useful useful to know if you could elevate; whereas IsUserAdmin tells you if you are elevated.

Similarly, you can have administrator rights, but not be a member of the administrators group. Use IsUserAdmin() to see if you currently actually have administrative rights.