473,729 Members | 2,155 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get list of the Groups a User belongs to

How can I get a list of the Groups both Local and Domain groups a User
belongs to.
Dec 9 '06 #1
10 26805
Hi,

On a Windows Server 2003 domain you can construct a WindowsIdentity by
passing in the user's name in the form, name@domain:

"WindowsIdentit y(String) Constructor"
http://msdn2.microsoft.com/en-us/library/td3046fc.aspx

Then you can access the Groups property (2.0 framework only):

"WindowsIdentit y.Groups Property"
http://msdn2.microsoft.com/en-us/lib...ty.groups.aspx

If you can't use the above solution since you are using a different version
of the framework or a different domain then I think you'll have to resort to
the unmanaged APIs such as LogonUser:

"LogonUser"
http://msdn2.microsoft.com/en-us/library/aa378184.aspx

The above will get you the User's token, which you can pass to the following
function:

"GetTokenInform ation"
http://msdn2.microsoft.com/en-us/library/aa446671.aspx

Specify the value of TOKEN_GROUPS for the TokenInformatio nClass argument.

(Note that I haven't used these APIs myself)

You'll have to use P/Invoke for this, of course :)

--
Dave Sexton

"Jeff Williams" <je***********@ hardsoft.com.au wrote in message
news:12******** *****@corp.supe rnews.com...
How can I get a list of the Groups both Local and Domain groups a User
belongs to.

Dec 9 '06 #2
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:uT******** *****@TK2MSFTNG P02.phx.gbl...
You'll have to use P/Invoke for this, of course :)
System.Director yServices will do all of this, and much more, for you without
recourse to p/invoke...

using System;
using System.Collecti ons.Generic;
using System.Director yServices;

public static List<stringGetG roupsForUser(st ring pstrUser)
{
/// <summary>
/// Gets the groups a user is a member of
/// </summary>
/// <param name="pstrGroup ">ActiveDirecto ry group to evaluate</param>
/// <returns>List<s tringof groups for pstrUser</returns>

DirectorySearch er objDS = null;
SearchResult objSR = null;
DirectoryEntry objUser = null;
List<stringlstG roups = new List<string>();

try
{
objDS = new DirectorySearch er("objectCateg ory=User");
objDS.Filter = "(SAMAccountNam e=" + pstrUser + ")";
objSR = objDS.FindOne() ;
objUser = new DirectoryEntry( objSR.Path);

PropertyCollect ion colProperties = objUser.Propert ies;
PropertyValueCo llection colPropertyValu es = colProperties["memberOf"];
foreach (string strGroup in colPropertyValu es)
{
lstGroups.Add(G etSAMAccountNam e(strGroup).ToL ower());
}
return lstGroups;
}
catch (Exception)
{
throw;
}
finally
{
if (objUser != null)
{
objUser.Close() ;
objUser.Dispose ();
objUser = null;
}
if (objSR != null)
{
objSR = null;
}
if (objDS != null)
{
objDS.Dispose() ;
objDS = null;
}
}
}

public static string GetSAMAccountNa me(string pstrPath)
{
/// <summary>
/// Gets a SAM Account Name from a given LDAP path
/// </summary>
/// <param name="pstrPath" >LDAP path to bind to</param>

DirectoryEntry objADEntry = null;

try
{
objADEntry = new DirectoryEntry( "LDAP://" + pstrPath);
return objADEntry.Prop erties["SAMAccountName "].Value.ToString ();
}
catch (System.Runtime .InteropService s.COMException)
{
return String.Empty;
}
catch (System.NullRef erenceException )
{
return String.Empty;
}
catch (Exception)
{
throw;
}
finally
{
if (objADEntry != null)
{
objADEntry.Clos e();
objADEntry.Disp ose();
objADEntry = null;
}
}
}
Dec 9 '06 #3
"Mark Rae" <ma**@markNOSPA Mrae.comwrote in message
news:OH******** ******@TK2MSFTN GP04.phx.gbl...
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:uT******** *****@TK2MSFTNG P02.phx.gbl...
>You'll have to use P/Invoke for this, of course :)

System.Director yServices will do all of this, and much more, for you without recourse to
p/invoke...

using System;
using System.Collecti ons.Generic;
using System.Director yServices;

public static List<stringGetG roupsForUser(st ring pstrUser)
{
/// <summary>
/// Gets the groups a user is a member of
/// </summary>
/// <param name="pstrGroup ">ActiveDirecto ry group to evaluate</param>
/// <returns>List<s tringof groups for pstrUser</returns>

DirectorySearch er objDS = null;
SearchResult objSR = null;
DirectoryEntry objUser = null;
List<stringlstG roups = new List<string>();

try
{
objDS = new DirectorySearch er("objectCateg ory=User");
objDS.Filter = "(SAMAccountNam e=" + pstrUser + ")";
objSR = objDS.FindOne() ;
objUser = new DirectoryEntry( objSR.Path);

PropertyCollect ion colProperties = objUser.Propert ies;
PropertyValueCo llection colPropertyValu es = colProperties["memberOf"];
foreach (string strGroup in colPropertyValu es)
{
lstGroups.Add(G etSAMAccountNam e(strGroup).ToL ower());
}
return lstGroups;
}
catch (Exception)
{
throw;
}
finally
{
if (objUser != null)
{
objUser.Close() ;
objUser.Dispose ();
objUser = null;
}
if (objSR != null)
{
objSR = null;
}
if (objDS != null)
{
objDS.Dispose() ;
objDS = null;
}
}
}

public static string GetSAMAccountNa me(string pstrPath)
{
/// <summary>
/// Gets a SAM Account Name from a given LDAP path
/// </summary>
/// <param name="pstrPath" >LDAP path to bind to</param>

DirectoryEntry objADEntry = null;

try
{
objADEntry = new DirectoryEntry( "LDAP://" + pstrPath);
return objADEntry.Prop erties["SAMAccountName "].Value.ToString ();
}
catch (System.Runtime .InteropService s.COMException)
{
return String.Empty;
}
catch (System.NullRef erenceException )
{
return String.Empty;
}
catch (Exception)
{
throw;
}
finally
{
if (objADEntry != null)
{
objADEntry.Clos e();
objADEntry.Disp ose();
objADEntry = null;
}
}
}
Just a few remarks:
You may simplify your code and make it easier to read and maintain by applying the *using*
idiom, this way, you get rid of the Dispose, Close and completely redundant "obj = null"
calls.
Your code will only work when the caller is running in his domain account, when this is not
the case, you need to bind explicitly against the Domain or the DC, and preferably using
FastBind for performance reasons. You may also bind to the GC (the Global Catalog) using
GC://... in order to speed-up the queries.
Another point to consider is that the binding user must have "query" privileges to all of
the objects you query, normally all domain member do have this privilege, but highly secured
AD's may restrict access to some objects to special accounts only. So it's possible that a
user can bind to his user object, but not to (some) of the related objects.
You should also try to reuse the already established DirectoryEntry object for further
operations against the AD, the way you do forces adsi to rebind and this can be a costly
operation especially on slow connections and uses a lot more resources at the LDAP server.
The following code snip shows how to take advantage of a single bind by using the
GetDirectorEntr y() for each successive object retrieval.

public static List<stringGetG roupsForUser(st ring userAccount)
{
string rootPath = "LDAP://{0}/DC=xxx,DC=yyy,D C=zzz";
string accountDomain = "domain"; // domain name or dc name or empty when binding to
logon domain
string userAccount = userAccount
rootPath = String.Format(
rootPath

, accountDomain);
string authUser = "xxx\yyyyy" ; // account used to bind, here hardcoded, not
production safe!
string authPassword = "PASSWORD"; // his password, here hardcoded, not production
safe!

List<stringlstG roups = new List<string>();
using (DirectoryEntry root = new DirectoryEntry( rootPath, authUser, authPassword,
AuthenticationT ypes.FastBind))
{
using (DirectorySearc her ds = new DirectorySearch er(root))
{
SearchResult sr = null;
ds.Filter = "(SAMAccountNam e=" + userAccount + ")";
sr = ds.FindOne();
using (DirectoryEntry user = sr.GetDirectory Entry())
{
PropertyCollect ion pcoll = user.Properties ;
PropertyValueCo llection memberOf = pcoll["memberOf"];
foreach (string cnGroup in memberOf)
{
ds.Filter = cnGroup.Substri ng(0, cnGroup.IndexOf (','));
sr = ds.FindOne();
using (DirectoryEntry group = sr.GetDirectory Entry())
{
lstGroups.Add(g roup.Properties["SAMAccountName "].Value.ToString ());
}
}
}
}
}
return lstGroups;
}
....

Willy.

Dec 9 '06 #4
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:ui******** ******@TK2MSFTN GP04.phx.gbl...
You may simplify your code... <snip>
It's not actually my code - I just found it on the web with a simple Google
search...
Dec 9 '06 #5
Hi Mark,

Good stuff, but correct me if I'm wrong here. That won't get the local
groups so the user will still have to use my method anyway.

--
Dave Sexton

"Mark Rae" <ma**@markNOSPA Mrae.comwrote in message
news:OH******** ******@TK2MSFTN GP04.phx.gbl...
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:uT******** *****@TK2MSFTNG P02.phx.gbl...
>You'll have to use P/Invoke for this, of course :)

System.Director yServices will do all of this, and much more, for you
without recourse to p/invoke...

using System;
using System.Collecti ons.Generic;
using System.Director yServices;

public static List<stringGetG roupsForUser(st ring pstrUser)
{
/// <summary>
/// Gets the groups a user is a member of
/// </summary>
/// <param name="pstrGroup ">ActiveDirecto ry group to evaluate</param>
/// <returns>List<s tringof groups for pstrUser</returns>

DirectorySearch er objDS = null;
SearchResult objSR = null;
DirectoryEntry objUser = null;
List<stringlstG roups = new List<string>();

try
{
objDS = new DirectorySearch er("objectCateg ory=User");
objDS.Filter = "(SAMAccountNam e=" + pstrUser + ")";
objSR = objDS.FindOne() ;
objUser = new DirectoryEntry( objSR.Path);

PropertyCollect ion colProperties = objUser.Propert ies;
PropertyValueCo llection colPropertyValu es = colProperties["memberOf"];
foreach (string strGroup in colPropertyValu es)
{
lstGroups.Add(G etSAMAccountNam e(strGroup).ToL ower());
}
return lstGroups;
}
catch (Exception)
{
throw;
}
finally
{
if (objUser != null)
{
objUser.Close() ;
objUser.Dispose ();
objUser = null;
}
if (objSR != null)
{
objSR = null;
}
if (objDS != null)
{
objDS.Dispose() ;
objDS = null;
}
}
}

public static string GetSAMAccountNa me(string pstrPath)
{
/// <summary>
/// Gets a SAM Account Name from a given LDAP path
/// </summary>
/// <param name="pstrPath" >LDAP path to bind to</param>

DirectoryEntry objADEntry = null;

try
{
objADEntry = new DirectoryEntry( "LDAP://" + pstrPath);
return objADEntry.Prop erties["SAMAccountName "].Value.ToString ();
}
catch (System.Runtime .InteropService s.COMException)
{
return String.Empty;
}
catch (System.NullRef erenceException )
{
return String.Empty;
}
catch (Exception)
{
throw;
}
finally
{
if (objADEntry != null)
{
objADEntry.Clos e();
objADEntry.Disp ose();
objADEntry = null;
}
}
}

Dec 9 '06 #6
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:ui******** ******@TK2MSFTN GP04.phx.gbl...
Good stuff, but correct me if I'm wrong here. That won't get the local
groups so the user will still have to use my method anyway.
No it won't, but it can with a fairly trivial modification:
http://www.experts-exchange.com/Prog..._20658471.html
Dec 9 '06 #7
Hi Mark,

That's great :)

--
Dave Sexton

"Mark Rae" <ma**@markNOSPA Mrae.comwrote in message
news:uG******** ******@TK2MSFTN GP06.phx.gbl...
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:ui******** ******@TK2MSFTN GP04.phx.gbl...
>Good stuff, but correct me if I'm wrong here. That won't get the local
groups so the user will still have to use my method anyway.

No it won't, but it can with a fairly trivial modification:
http://www.experts-exchange.com/Prog..._20658471.html

Dec 9 '06 #8
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:eR******** ******@TK2MSFTN GP02.phx.gbl...
That's great :)
By the way, if you do intend to use the code I found, be sure to follow
Willy's recommended modifications.. .
Dec 9 '06 #9
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:ui******** ******@TK2MSFTN GP04.phx.gbl...
Hi Mark,

Good stuff, but correct me if I'm wrong here. That won't get the local groups so the user
will still have to use my method anyway.

--

No, you can use the WinNT provider to connect to the local SAM, like this:

private static List<stringAcco untGroups(strin g userAccount)
{
List<stringlstG roups = new List<string>(10 );
string adsPath = "WinNT://<domain>/<machine>"; // or WinNT://<machine if not a
domain member.
using (DirectoryEntry groupEntry = new DirectoryEntry( adsPath +",computer" ))
{
IADsContainer cont = groupEntry.Nati veObject as IADsContainer;
object[] filter = {"Group"};
cont.Filter = filter;
foreach (IADsGroup group in cont) {
if(group.IsMemb er(adsPath + "/" + userAccount))
lstGroups.Add(g roup.Name);
}
}
return lstGroups;
}

the problem here is that you need to set a reference to activeds.tlb. Also note that the
above sample does not account for nested groups!!
Note that you can also use WindowsIdentity .Groups, the problem here is that you also get the
pseudo accounts returned.

A better solution is to use System.Manageme nt (and WMI classes "Win32_UserAcco unt" and
"Win32_Grou p") to check local account and group membership.
Willy.

Dec 9 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1409
by: Bas | last post by:
I need to know if there is a way in Microsoft SQL Server 2000 to determine which Windows groups a user belongs to if logging into the database under Windows Authentication. I am making a tool to view all permissions of a user, but since most permissions are granted through groups here, I need to find an efficient way to look this up. Thanks in advance, Bas
3
372
by: RCCNH | last post by:
I am creating a Windows application using C# in .NET. In one of the windows, I have to show a scrollable list of user objects. Those user objects contain various controls themselves (textbox, buttons, etc) and are all of the same type of user object - just showing different data. In this case, each one is a "question" being presented that needs to be answered, and the requirement is to be able to show all the questions for a given...
3
2315
by: Gonçalo Boléo | last post by:
How do i list the groups a user belong using AD? thanks, Gonçalo Boléo
1
3612
by: Mad Scientist Jr | last post by:
I would like to write a vb.asp.net function Private Function fn_sGetRoles(byval sDelimiter as string) As String that simply returns a delimited list of all the roles a user belongs to. I did some research, and found a number of solutions, that all seem to use a WindowsIdentity type object. However, when I try to convert
2
2147
by: Kevin Wen | last post by:
Hi Sirs, How could i determine if an user belongs to a specific group, especially nested group. thanks, -Kevin
3
2325
by: Matt | last post by:
I am trying to write some code that will find all the groups that a user is a member of Does anyone know how to do this in VB.NET Thanks in advanc Matt
8
3589
by: tlyczko | last post by:
I am developing an Access database that will be used by some users logging into Citrix servers. Using the "Code 1" listing, 'fGetFullNameOfLoggedUser' from Dev Ashish's site, which I found in this thread: http://groups.google.com/group/comp.databases.ms-access/browse_thread/thread/9ba1a9bc7ebc270e/36aeea7d08d31849#36aeea7d08d31849 subject: Question about 'fGetFullNameOfLoggedUser' I implemented this as the control source of a simple...
4
2014
by: Cleyton | last post by:
Hello! I need to get the user groups in a machine, because i need to verify dynamically what's the name of the group "Everyone" in different windows. For example, in windows in portuguese the name of the user group "Everyone" is "Todos", so i need to know what's the name of this user group. Someone have an example of how can I do this??
4
3709
by: Dan | last post by:
Hi Group Memebers: I am pretty new to asp.net.vb. Please dont mistake me if my Q is silly... I want to list the user names online in home page.... I am adopting this metod: Get the user name after login and insert the names in a table who log
0
8767
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9293
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9221
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9162
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4799
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3246
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2171
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.