Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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..
Posted
Updated 29-Sep-16 11:47am
Comments
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.

 
Share this answer
 
This is the simplest solution that I can find.
C#
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.
 
Share this answer
 
v2
<DllImport("shell32.dll", SetLastError:=True)> _
Public Function IsUserAnAdmin() As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900