Asp.net Forms Authentication against Particular Active Directory Security Group

Hello,

I would like to authentiate all members of the particular Active Directory Security Group using Forms Authentication. I referred this link
http://support.microsoft.com/default.aspx?scid=kb;en-us;316748
 which helped me to authenticate all members of whole Active Directory. Can any one please help me what are the changes needed to authenticate against particular AD Security Groups.

Thanks in Advance
pravin_bas2kAsked:
Who is Participating?
 
Ted BouskillConnect With a Mentor Senior Software DeveloperCommented:
Something doesn't add up.  If you are getting the opposite expected results there must be a conditional statement that is backward somewhere in your code.
0
 
Ted BouskillSenior Software DeveloperCommented:
That sample actually includes how to determine if a user is a member of a group.  It returns a list of the groups for the user using GetGroups()  If you know the group name you could compare it to that list.

Otherwise you need to use the filter: search.Filter = "(SAMAccountName=" + username + ")";

That filter is an LDAP query:  search.Filter = "(&(SAMAccountName=" + username + ")(memberOf=CN=My Group,OU=Branch,DC=mydomain,DC=com))";

The format of the memberOf filter changes based on the group, that is an example.  I'd do some research on writing LDAP queries.

0
 
pravin_bas2kAuthor Commented:
Thanks for the close answer that i am looking for. Please assist me on the further doubts.

Is it changing the LDAP query alone is enough or does it need any further changes on the LdapAuthentication.cs

I want to check against the security group named 'boardusers' in the domain "blue.org"

I have included the LDAP query on the code. Please let assist me with the changes required.

using System;
using System.Text;
using System.Collections;
using System.DirectoryServices;

namespace FormsAuth
{      
  public class LdapAuthentication
  {
    private String _path;
    private String _filterAttribute;

    public LdapAuthentication(String path)
    {
      _path = path;
    }
            
    public bool IsAuthenticated(String domain, String username, String pwd)
    {
      String domainAndUsername = domain + @"\" + username;
      DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
                  
try
      {      //Bind to the native AdsObject to force authentication.                  
         Object obj = entry.NativeObject;

      DirectorySearcher search = new DirectorySearcher(entry);

      search.Filter = "(&(SAMAccountName=" + username + ")(memberOf=CN=Boardusers,OU=Security Groups,DC=blue,DC=org))";

      search.PropertiesToLoad.Add("cn");
      SearchResult result = search.FindOne();

      if(null == result)
      {
          return false;
      }

      //Update the new path to the user in the directory.
      _path = result.Path;
      _filterAttribute = (String)result.Properties["cn"][0];
      }
      catch (Exception ex)
      {
        throw new Exception("Error authenticating user. " + ex.Message);
      }

      return true;
     }

     public String GetGroups()
     {
       DirectorySearcher search = new DirectorySearcher(_path);
       search.Filter = "(cn=" + _filterAttribute + ")";
       search.PropertiesToLoad.Add("memberOf");
       StringBuilder groupNames = new StringBuilder();

       try
       {
         SearchResult result = search.FindOne();

       int propertyCount = result.Properties["memberOf"].Count;

          String dn;
       int equalsIndex, commaIndex;
                        
       for(int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
       {
         dn = (String)result.Properties["memberOf"][propertyCounter];

             equalsIndex = dn.IndexOf("=", 1);
         commaIndex = dn.IndexOf(",", 1);
         if(-1 == equalsIndex)
         {
           return null;
              }

           groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
         groupNames.Append("|");

           }
       }
       catch(Exception ex)
       {
         throw new Exception("Error obtaining group names. " + ex.Message);
       }                  
       return groupNames.ToString();
     }
   }
}

Also i need to make any changes in the Application_AuthenticateRequest Event handler in the Global.asax

 void Application_AuthenticateRequest(Object sender, EventArgs e)
{
  String cookieName = FormsAuthentication.FormsCookieName;
  HttpCookie authCookie = Context.Request.Cookies[cookieName];

  if(null == authCookie)
  {//There is no authentication cookie.
    return;
  }      
            
  FormsAuthenticationTicket authTicket = null;
      
  try
  {
    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
  }
  catch(Exception ex)
  {
    //Write the exception to the Event Log.
    return;
  }
      
  if(null == authTicket)
  {//Cookie failed to decrypt.
    return;            
  }            
      
  //When the ticket was created, the UserData property was assigned a
  //pipe-delimited string of group names.
  String[] groups = authTicket.UserData.Split(new char[]{'|'});

  //Create an Identity.
  GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
      
  //This principal flows throughout the request.
  GenericPrincipal principal = new GenericPrincipal(id, groups);

  Context.User = principal;
      
}
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Ted BouskillSenior Software DeveloperCommented:
Yep that is the correct way to write the LDAP query.   It should now work correctly.
0
 
pravin_bas2kAuthor Commented:
It does n't work. its authenticating other users who are not the member of boardusers group. what could be the reason?
0
 
Ted BouskillSenior Software DeveloperCommented:
Did you create the log in ASPX as shown in the sample?
0
 
pravin_bas2kAuthor Commented:
Yes. I created the Aspx page exactly with the same code in the link. I tested with two accounts which are the part of two different security groups. Apart from the boardusers group members, it authenticates other group members also.
0
All Courses

From novice to tech pro — start learning today.