Is user a member of the Administrators group

Sometimes it's important to know if application is running under account that is a member of the Administrators group. There're a few ways to accomplish that.

The easiest one is to use IsUserAnAdmin Function that's a wrapper for CheckTokenMembership Function

but Microsoft does not guaranty that it'll be available or unchanged after Windows Vista.

The second code sample shows how to use CheckTokenMembership function directly in conjunction with AllocateAndInitializeSid Function and FreeSid Function

Note 1 Agnes Beste pointed me to article How to deal with localized and renamed user and group names

. It lists other well-known users and groups and their aliases that can be used with CheckTokenMembership.

$SAMPLECODE$

1
2
3
4
5
6
* #1 
* IsUserAnAdmin function is a wrapper for CheckTokenMembership. 
*   It is recommended to call that function directly as shown later
DECLARE Long IsUserAnAdmin IN Shell32.dll
? IsUserAnAdmin() <> 0

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
* #2
* CheckTokenMembership function
? IsAdmin()
RETURN
*-----------------------

FUNCTION IsAdmin
#DEFINE SECURITY_NT_AUTHORITY 5
#DEFINE SECURITY_BUILTIN_DOMAIN_RID 0x20
#DEFINE DOMAIN_ALIAS_RID_ADMINS 0x220

DECLARE Long AllocateAndInitializeSid IN Advapi32.dll ;
		String pIdentifierAuthority, Short nSubAuthorityCount, ;
		Long dwSubAuthority0, Long dwSubAuthority1, Long dwSubAuthority2, ;
		Long dwSubAuthority3, Long dwSubAuthority4, Long dwSubAuthority5, ;
		Long dwSubAuthority6, Long dwSubAuthority7, Long @ pSid

DECLARE Long FreeSid IN Advapi32.dll Long pSid

DECLARE Long CheckTokenMembership IN Advapi32.dll Long TokenHandle, ;
	  	Long SidToCheck, Long @ IsMember

DECLARE Long GetLastError IN WIN32API

LOCAL lcpIdentifierAuthority, lnSid, lnIsMember
lcpIdentifierAuthority = REPLICATE(CHR(0),5) + CHR(SECURITY_NT_AUTHORITY ) 
lnSid = 0
llIsAdmin = .F.
IF AllocateAndInitializeSid(lcpIdentifierAuthority, ;
    	2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, ;
	    0, 0, 0, 0, 0, 0, @lnSid) <> 0
    
    lnIsMember = 0
    IF CheckTokenMembership( 0, lnSid, @lnIsMember)	<> 0 
    	IF lnIsMember <> 0
    		llIsAdmin = .T.
    	ENDIF	
    ELSE
	*? "CheckTokenMembership Error "  + apierror(GetLastError())
    ENDIF
    	
    = FreeSid(lnSid)
ELSE
	*? "AllocateAndInitializeSid Error "  + apierror(GetLastError())
ENDIF    

RETURN llIsAdmin 

Comments