Code to check to see if a user is a member of the Administrators group

wopfather

Member
Joined
Dec 10, 2007
Messages
5
Programming Experience
Beginner
I want to write an application that only allows certain users to access it based on their group membership, but i don't want to query the domain for their group memberships.

I have the following code:
VB.NET:
Dim wp As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())
        StatusBarPanel1.Text = wp.IsInRole("Administrators").ToString

but it is returning a false each time i run it. Even if i use the domain\ contex as below, it still comes up false.

VB.NET:
     Dim wp As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())
        StatusBarPanel1.Text = wp.IsInRole("domain1\Administrators").ToString

Any thoughts?
 
Imports statement is useful for such long namespaces:
VB.NET:
Imports System.Security.Principal
Then you have other overloads of IsInRole too, for example one that takes a parameter of the WindowsBuiltInRole enumeration type :
VB.NET:
Dim wp As New WindowsPrincipal(WindowsIdentity.GetCurrent())
StatusBarPanel1.Text = wp.IsInRole(WindowsBuiltInRole.Administrator).ToString
 
Thanks JohnH that worked, but can i check to see if the user is a member of other computer groups besides the built in groups? Can I check to see if the user is a member of any Domain groups?
 
That was the overload you tried; that takes a string parameter
For domain-specific roles, the role string should be in the form "DomainName\RoleNameHere"
In the .NET Framework version 1.1 and later, the role parameter is case-insensitive.
I think the role names are language specific, the enum values works for any language.
You could also have a look at the Groups of the WindowsIdentity:
VB.NET:
Dim wi As WindowsIdentity = WindowsIdentity.GetCurrent
For Each idref As IdentityReference In wi.Groups
    MsgBox(idref.Translate(GetType(NTAccount)).Value)
Next
 
My code is
VB.NET:
Dim wp As New WindowsPrincipal(WindowsIdentity.GetCurrent())
StatusBarPanel1.Text = wp.IsInRole("Domain1\mygroup").ToString

but it returns false even though the user i am logged in as is in this group.

I tried your sugestion

VB.NET:
Dim wi As WindowsIdentity = WindowsIdentity.GetCurrent
For Each idref As IdentityReference In wi.Groups
            MsgBox(idref.Translate(GetType(NTAccount)).Value)
        Next
    End Sub

But i get a syntax error for idref being undefined. Do i need to import any classes?
 
My bad, didn't notice you were using .Net 1.1. Groups property is new in .Net 2.0.
 

Latest posts

Back
Top