public virtual bool IsInRole(SecurityIdentifier sid)
{
if (sid == null)
throw new ArgumentNullException(nameof(sid));
Contract.EndContractBlock();
// special case the anonymous identity.
if (_identity.AccessToken.IsInvalid)
return false;
// CheckTokenMembership expects an impersonation token
SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle;
if (_identity.ImpersonationLevel == TokenImpersonationLevel.None)
{
if (!Interop.Advapi32.DuplicateTokenEx(_identity.AccessToken,
(uint)TokenAccessLevels.Query,
IntPtr.Zero,
(uint)TokenImpersonationLevel.Identification,
(uint)TokenType.TokenImpersonation,
ref token))
throw new SecurityException(new Win32Exception().Message);
}
bool isMember = false;
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
if (!Interop.Advapi32.CheckTokenMembership((_identity.ImpersonationLevel != TokenImpersonationLevel.None ? _identity.AccessToken : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
token.Dispose();
return isMember;
}