How can I find a user's group using AD authentication in aspx?

So I followed this tutorial and I can successfully login, but now I was trying to find out if a user belongs to a group, I've tried:

if (User.IsInRole("group"))

along with

enableSearchMethods="true"

Nothing seems to work though, perhaps I'm looking at the wrong place... Anyone has any tips?

Upvotes: 1

Views: 731

Answers (1)

marc_s
marc_s

Reputation: 754478

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here....
   PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();

   // enumerate the groups found - check to find your group in question
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Alternatively, you can also find the user and the group principals:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
GroupPrincipal groupToCheck = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

if(user != null && groupToCheck != null)
{
    // this call will tell you - yes or no - whether that user is member of that group
    bool isMember = user.IsMemberOf(groupToCheck); 
}

Upvotes: 1

Related Questions