Mar*_*rkP 5 c# ldap asp.net-mvc-3
我正在编写一个基于MVC(.NET 4.0)的网站,该网站需要我公司LDAP服务器的登录凭据.我的代码需要的是仅允许属于某个组的用户.例如,我可能正在寻找属于"企业IT"小组的用户.我的凭据可能是"系统管理员"组的一部分,该组是"企业IT"的子组.我正在使用表单身份验证.
如何以递归方式检查用户登录时所在的组?
对于搜索此类查询的其他人来说,以下是我在应用程序中的操作方法:
关键是1.2.840.113556.1.4.1941扩展搜索过滤器.由于此特定过滤器仅适用于DN,因此我首先获取要检查的用户的DN,然后查询组以查看此特定用户是否是链中任何组的成员.
internal const string UserNameSearchFilter = "(&(objectCategory=user)(objectClass=user)(|(userPrincipalName={0})(samAccountName={0})))";
internal const string MembershipFilter = "(&(objectCategory=group)(objectClass=group)(cn=MyGroup)(member:1.2.840.113556.1.4.1941:={0}))";
using (var de = new DirectoryEntry(AppSettings.LDAPRootContainer, AppSettings.AdminUser, AppSettings.AdminPassword, AuthenticationTypes.FastBind))
using (var ds = new DirectorySearcher(de) { Filter = string.Format(UserNameSearchFilter, username) })
{
ds.PropertiesToLoad.AddRange(new[] { "distinguishedName" });
var user = ds.FindOne();
if (user != null)
using (var gds = new DirectorySearcher(de) { PropertyNamesOnly = true, Filter = string.Format(MembershipFilter, user.Properties["distinguishedName"][0] as string) })
{
gds.PropertiesToLoad.AddRange(new[] { "objectGuid" });
return gds.FindOne() != null;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我发现将GroupPrincipal.GetMembers
与递归标志一起使用既快速又有效。
public bool IsMember(string groupName, string samAccountName)
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
using (UserPrincipal user = UserPrincipal.FindByIdentity(context, samAccountName))
using(GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName))
{
return group.GetMembers(true).OfType<Principal>().Any(u => u.SamAccountName.Equals(user.SamAccountName, StringComparison.InvariantCultureIgnoreCase));
}
}
Run Code Online (Sandbox Code Playgroud)
如果要检查特定用户的成员资格,请绑定到相关 AD 对象并检索tokenGroups属性。它包含二进制形式的所有直接和间接组成员身份 - 它是一个字节数组的数组。每个字节数组都可以传递给 SecurityIdentifier 类的构造函数,然后转换为包含明文组名称的 NTAccount。
var sids = new IdentityReferenceCollection();
foreach (byte[] group in tokenGroups)
{
sids.Add(new SecurityIdentifier(group, 0));
}
var accounts = sids.Translate(typeof(NTAccount));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4236 次 |
最近记录: |