Mirror

Check if a user has administrator rights in NT (Views: 100)

Problem/Question/Abstract:

How to check if a user has administrator rights in NT

Answer:

Solve 1:

{ ... }
const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));

const
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;

function IsAdmin: Boolean;
var
hAccessToken: THandle;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
x: Integer;
bSuccess: BOOL;
begin
Result := False;
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken);
if not bSuccess then
begin
if GetLastError = ERROR_NO_TOKEN then
bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken);
end;
if bSuccess then
begin
GetMem(ptgGroups, 1024);
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups,
1024, dwInfoBufferSize);
CloseHandle(hAccessToken);
if bSuccess then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators);
for x := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then
begin
Result := True;
Break;
end;
FreeSid(psidAdministrators);
end;
FreeMem(ptgGroups);
end;
end;


Solve 2:

function IsAdmin: boolean;
{Returns a boolean indicating whether or not user has admin privileges.
Call only when running under NT.}
var
hAccessToken: THandle;
ptgGroups: pTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
i: integer; {counter}
blnResult: boolean; {return flag}
const
SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = (Value: (0, 0, 0, 0, 0, 5));
{ntifs}
SECURITY_BUILTIN_DOMAIN_RID: DWORD = $00000020;
DOMAIN_ALIAS_RID_ADMINS: DWORD = $00000220;
DOMAIN_ALIAS_RID_USERS: DWORD = $00000221;
DOMAIN_ALIAS_RID_GUESTS: DWORD = $00000222;
DOMAIN_ALIAS_RID_POWER: DWORD = $000002203;
begin
if Win32Platform <> VER_PLATFORM_WIN32_NT then
begin
Result := True;
Exit;
end;
Result := False;
ptgGroups := nil;
blnResult := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken);
if not blnResult then
begin
if GetLastError = ERROR_NO_TOKEN then
blnResult := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken);
end;
if blnResult then
try
GetMem(ptgGroups, 1024);
blnResult := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups,
1024, dwInfoBufferSize);
CloseHandle(hAccessToken);
if blnResult then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators);
{$R-}
for i := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[i].Sid) then
begin
Result := True;
Break;
end;
{$IFDEF RPLUS}{$R+}{$ENDIF}
FreeSid(psidAdministrators);
end;
finally;
if ptgGroups <> nil then
FreeMem(ptgGroups);
end;
end;



<< Back to main page