如何从Active Directory获取正确的数据以进行身份​​验证

时间:2011-05-18 09:51:22

标签: c# wcf active-directory ldap

我有一个客户端服务解决方案,其中包含Winforms客户端应用程序和IIS中托管的WCF服务。

在WCF服务中,我可以使用自定义WindowsIdentity.Name轻松提取在客户端登录的当前用户名(IAuthorizationPolicy)。这是通过从Evaluate方法中的传入WindowsIdentity获取EvaluationContext来完成的。

WindowsIdentity.Name看起来像这样:MyCompanyGroup\MyName

为了能够在我自己的成员资格模型中绑定到AD帐户,我需要能够让用户在Winforms客户端上选择要绑定的AD用户。要提取树的AD组和用户,我使用以下代码:

public static class ActiveDirectoryHandler
{
  public static List<ActiveDirectoryTreeNode> GetGroups()
  {
    DirectoryEntry objADAM = default(DirectoryEntry);
    // Binding object. 
    DirectoryEntry objGroupEntry = default(DirectoryEntry);
    // Group Results. 
    DirectorySearcher objSearchADAM = default(DirectorySearcher);
    // Search object. 
    SearchResultCollection objSearchResults = default(SearchResultCollection);
    // Results collection. 
    string strPath = null;
    // Binding path. 
    List<ActiveDirectoryTreeNode> result = new List<ActiveDirectoryTreeNode>();

    // Construct the binding string. 
    strPath = "LDAP://stefanserver.stefannet.local";
    //Change to your ADserver 

    // Get the AD LDS object. 
    try
    {
        objADAM = new DirectoryEntry();//strPath);
        objADAM.RefreshCache();
    }
    catch (Exception e)
    {
        throw e;
    }

    // Get search object, specify filter and scope, 
    // perform search. 
    try
    {
        objSearchADAM = new DirectorySearcher(objADAM);
        objSearchADAM.Filter = "(&(objectClass=group))";
        objSearchADAM.SearchScope = SearchScope.Subtree;
        objSearchResults = objSearchADAM.FindAll();
    }
    catch (Exception e)
    {
        throw e;
    }

    // Enumerate groups 
    try
    {
        if (objSearchResults.Count != 0)
        {
            //SearchResult objResult = default(SearchResult);
            foreach (SearchResult objResult in objSearchResults)
            {
                objGroupEntry = objResult.GetDirectoryEntry();
                result.Add(new ActiveDirectoryTreeNode() { Id = objGroupEntry.Guid, ParentId = objGroupEntry.Parent.Guid, Text = objGroupEntry.Name, Type = ActiveDirectoryType.Group, PickableNode = false });

                foreach (object child in objGroupEntry.Properties["member"])
                    result.Add(new ActiveDirectoryTreeNode() { Id= Guid.NewGuid(), ParentId = objGroupEntry.Guid, Text = child.ToString(), Type = ActiveDirectoryType.User, PickableNode = true });
            }
        }
        else
        {
            throw new Exception("No groups found");
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }

    return result;
  } 
}

public class ActiveDirectoryTreeNode : ISearchable
{
    private Boolean _pickableNode = false;
#region Properties
[GenericTreeColumn(GenericTableDescriptionAttribute.MemberTypeEnum.TextBox, 0, VisibleInListMode = false, Editable = false)]
public Guid Id { get; set; }
[GenericTreeColumn(GenericTableDescriptionAttribute.MemberTypeEnum.TextBox, 1, VisibleInListMode = false, Editable = false)]
public Guid ParentId { get; set; }
[GenericTreeColumn(GenericTableDescriptionAttribute.MemberTypeEnum.TextBox, 2, Editable = false)]
public string Text { get; set; }
public ActiveDirectoryType Type { get; set; }
#endregion

#region ISearchable
public string SearchString
{
    get { return Text.ToLower(); }
}

public bool PickableNode
{
    get { return _pickableNode; }
    set { _pickableNode = value; }
}
#endregion

}

public enum ActiveDirectoryType
{
    Group,
    User
}

树可能看起来像这样:

CN=Users*
- CN=Domain Guests,CN=Users,DC=MyCompany,DC=local
- CN=5-1-5-11,CN=ForeignSecurityPrinipals,DC=MyCompany,DC=local
...
CN=Domain Admins
- CN=MyName,CN=Users,DC=MyCompany,DC=local
...

(* =组)

名称格式不同,我看不出如何将其与服务上的名称进行比较。

那么如何为树提取适当的Active Directory数据?

1 个答案:

答案 0 :(得分:1)

我无法理解你要问的是什么,但我希望你能找到一些有用的信息。

您在服务上看到的登录名(即“MyName”)对应于AD中名为sAMAccountName的属性。您可以从DirectoryEntry通过Properties集合提取sAMAccountName。例如,如果您要为群组中的每个成员显示sAMAccountName,则可以执行以下操作:

var objSearchADAM = new DirectorySearcher();
objSearchADAM.Filter = "(&(objectClass=group))";
objSearchADAM.SearchScope = SearchScope.Subtree;
var objSearchResults = objSearchADAM.FindAll();

foreach (SearchResult objResult in objSearchResults)
{
    using (var objGroupEntry = objResult.GetDirectoryEntry())
    {
        foreach (string child in objGroupEntry.Properties["member"])
        {
            var path = "LDAP://" + child.Replace("/", "\\/");
            using (var memberEntry = new DirectoryEntry(path))
            {
                if (memberEntry.Properties.Contains("sAMAccountName"))
                {
                    // Get sAMAccountName
                    string sAMAccountName = memberEntry.Properties["sAMAccountName"][0].ToString();
                    Console.WriteLine(sAMAccountName);
                }

                if (memberEntry.Properties.Contains("objectSid"))
                {
                    // Get objectSid
                    byte[] sidBytes = (byte[]) memberEntry.Properties["objectSid"][0];
                    var sid = new System.Security.Principal.SecurityIdentifier(sidBytes, 0);
                    Console.WriteLine(sid.ToString());
                }
            }
        }
    }
}

您可能还会发现UserPrincipal很有趣。使用此类,您可以使用FindByIdentity方法轻松连接到AD中的用户对象,如下所示:

var ctx = new PrincipalContext(ContextType.Domain, null);
using (var up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MyName"))
{
    Console.WriteLine(up.DistinguishedName);
    Console.WriteLine(up.SamAccountName);

    // Print groups that this user is a member of
    foreach (var group in up.GetGroups())
    {
        Console.WriteLine(group.SamAccountName);
    }
}