Check if current user is domain administrator
Querying your enterprise domain groups
The scenario
In business applications it’s very common checking if the current user is member of the ‘domain administrators’ role of your company. For example, recently I had to check if the current user has administrative privileges in order to show some advanced configuration options.
IsInRole
To acomplish this we could use the IsInRole method from the WindowsPrincipal class. This method checks if an user is member of a Windows role and returns a bool value. One of its overrides allows to pass the SID of the role or a constant value based on the enumeration WindowsBuiltInrole.
Note: For performance reasons, it’s recommended to use the override: IsinRole(SecurityIdentifier).
To check if current user is an administrator on the local computer we only need to do this:
|
|
Notice that it’s realy easy, but WindowsBuiltInrole enumeration only contains local roles. So, if we would check if our user is member of a domain group, we should find the role SID in our domain.
WellKnownSidType
Let’s take a look at the following enumeration WellKnownSidType, this enumeration provides commonly used security identifiers and that’s exactly whan we want. Let’s try to use it in our code:
|
|
Do’h! It seems that we need to pass the second argument called DomainSId, which represents the security identifier of your company domain.
DomainSid
This domain SID is required for some WellKnownSidType values and we can get it using the DirectoryEntry class from the assembly System.DirectoryServices.
|
|
First, we obtain a reference to the domain using the domain name. Then get of the value the property objectSid as a byte array, and finally transform this value into a valid SecurityIdentifier which is what we need.
Show me the code
Putting it all together. Like my collegue and friend @alegrebandolero I’m also a fan of extension methods. So, let’s create an extension method for the WindowsIdentity class:
|
|
That’s all. Now, use it as follows:
|
|
Edit 12/14/2010: Since Windows Vista each Windows user have a couple of security tokens. The first one is the normal token with limited privileges, and the second one only works when you ‘run as administrator’. This code only works if you are using the second token, running the application as administrator.
HYEI, happy coding!
December 2010