如何从活动目录获取正确的数据进行身份验证
本文关键字:数据 身份验证 获取 活动 | 更新日期: 2023-09-27 17:56:41
我有一个客户端服务解决方案,其中包含一个 Winforms 客户端应用程序和一个在 IIS 中承载的 WCF 服务。
在 WCF 服务中,我可以使用自定义IAuthorizationPolicy
轻松地提取在客户端登录的当前用户名 (WindowsIdentity.Name
)。这是通过在 Evaluate 方法中获取传入EvaluationContext
WindowsIdentity
来完成的。
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
...
(* = 组)
该名称的格式不同,我看不出如何将其与服务上的名称进行比较。
那么如何为树提取正确的活动目录数据呢?
我不能声称理解你在问什么,但这里有一些信息,我希望你能找到帮助。
您在服务上看到的登录名称(即"MyName")对应于 AD 中名为 sAMAccountName
的属性。 您可以从DirectoryEntry
中提取sAMAccountName
Properties
集合。 例如,如果要显示组中每个成员的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);
}
}