Click here to Skip to main content
14,664,421 members
Rate this:
Please Sign up or sign in to vote.
See more:
I want to check whether logged in user have admin rights.
I am developing console application in ASP.NET 4.5.2, C#, Visual Studio 2015.

I log in as Domain user, having Admin rights.

What I have tried:

Tried several code samples available on google, but none seems to work. Below are couple of samples.

//Sample # 1

return WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellknownSidType.BuiltinAdministratorsSid);

//Sample # 2
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrinciipal principal = new WindowsPrincipal(identity);
return princiapl.IsInRole(WindowsBuiltInRole.Administrator);

Above code returns true, only if Visual Studio 2015 is run as administrator else it will always return false.

I want application to return true, if logged in user have admin rights, despite of fact VS 2015 run as administrator or not..
Updated 29-Sep-16 11:47am
F-ES Sitecore 29-Sep-16 4:09am
Is it the client\user of the website who you want to check has admin rights?
phil.o 29-Sep-16 4:59am
A console application in ASP.NET? That sounds weird. Please describe your project more acutely.
[no name] 29-Sep-16 8:41am
You need to figure out what you are doing first or trying to do. "console application in ASP.NET 4.5.2, C#" tells us that you have no idea what it is that you are doing or trying to do.

Rate this:
Please Sign up or sign in to vote.

Solution 1

Rate this:
Please Sign up or sign in to vote.

Solution 2

This is the simplest solution that I can find.
using System.DirectoryServices.AccountManagement; // in reference dll

public bool UserIsAdmin(string userSamAccountName, string adminSamAccountName)
 PrincipalContext context =  new PricipalContext(ContextType.Domain);
 GroupPrincipal adminGroup = new GroupPricipal(context, adminSamAccountName);
 UserPrincipal user = UserPrincipal.FindByIdentity(context, userSamAccountName);
 return user.IsMemberOf(adminGroup);

Edit: now be carefull, you don't want to leave the samAccount name of your domain admin group just lying about on the server if it is facing the internet.
Rate this:
Please Sign up or sign in to vote.

Solution 3

<DllImport("shell32.dll", SetLastError:=True)> _
Public Function IsUserAnAdmin() As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100