CheckTokenMembership (advapi32)
Last changed: -202.123.20.55

.
Summary
Determines whether a specified SID is enabled in an access token

C# Signature:

[DllImport("advapi32.dll", SetLastError=true)]
static extern bool CheckTokenMembership(IntPtr TokenHandle, IntPtr SidToCheck, out bool IsMember);

User-Defined Types:

None.

VB.Net Signature

    Declare Function CheckTokenMembership Lib "advapi32.dll" ( _
    ByVal TokenHandle As IntPtr, _
    ByVal SidToCheck As IntPtr, _
    ByRef IsMember As Boolean _
    ) As Boolean

Notes:

    'BOOL CheckTokenMembership(
    '  HANDLE TokenHandle,
    '  PSID SidToCheck,
    '  PBOOL IsMember
    ');

Tips & Tricks:

Please add some!

VB.Net Sample Code:

    Dim LogonProvider, LogonType As Integer
    Dim Token, ImpersonatedToken, AdminGroup As IntPtr
    Dim NtAuthority As SID_IDENTIFIER_AUTHORITY
    Dim IsAdmin As Boolean

    LogonType = LOGON32_LOGON_INTERACTIVE
    LogonProvider = LOGON32_PROVIDER_DEFAULT
    ReDim NtAuthority.Value(6)
    NtAuthority.Value(5) = SECURITY_NT_AUTHORITY

    ' First step is to validate the credentials
    If Not LogonUser(strUser, strDomain, strPassword, LogonType, LogonProvider, Token) Then
        MsgBox("Couldn't validate user with provided credentials")
        Exit Sub
    End If

    ' Next we create an impersonation token
    If Not DuplicateToken(Token, SECURITY_IMPERSONATION, ImpersonatedToken) Then
        MsgBox("Yikes, couldn't impersonate the user")
        Exit Sub
    End If

    ' Next we build the SID for the local Administrators group
    If Not AllocateAndInitializeSid(NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, AdminGroup) Then
        MsgBox("Yikes, couldn't create the Local Admininstrator Group's SID")
        Exit Sub
    End If

    ' Lastly, we check to see if the impersonated token is in the Admin Group
    If Not CheckTokenMembership(ImpersonatedToken, AdminGroup, IsAdmin) Then
        MsgBox("Yikes, couldn't check membership")
        Exit Sub
    End If

    FreeSid(AdminGroup)
    MsgBox("IsAdmin=" & IsAdmin)

Alternative Managed API:

Do you know one? Please contribute it!

Documentation