2011-01-26 81 views
3

我正在创建一个LDAP类,其中包含一个返回当前用户的管理员用户名的函数。LDAP管理器属性

我知道,我可以用“经理”属性返回CN =“名字”,OU =“组”,DC =“公司”等

我特别想要的管理者用户名,没有人知道如果有一个属性字符串我可以发送到LDAP,只有特定的管理员用户名?如果没有,是否有其他方法可以这样做?

回答

1

我已经想出了现在的解决方案。

基本上,LDAP中的manager属性检索了maanger用户的distinguishedName属性。

因此,如果我搜索包含经理返回的distinguishedName的用户的LDAP,那么我可以通过这种方式获得他们的任何属性。

1

一个可行的办法是使用这样的事情 - 这需要你在.NET 3.5和你同时参照System.DirectoryServices以及System.DirectoryServices.AccountManagement

// return manager for a given user 
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user) 
{ 
    UserPrincipal result = null; 

    if (user != null) 
    { 
     // get the DirectoryEntry behind the UserPrincipal object 
     DirectoryEntry dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry; 

     if (dirEntryForUser != null) 
     { 
      // check to see if we have a manager name - if so, grab it 
      if (dirEntryForUser.Properties["manager"] != null) 
      { 
       string managerDN = dirEntryForUser.Properties["manager"][0].ToString(); 

       // find the manager UserPrincipal via the managerDN 
       result = UserPrincipal.FindByIdentity(ctx, managerDN); 
      } 
     } 
    } 

    return result; 
} 

然后你可以调用这个方法例如像这样:

// Create default domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// find yourself - you could also search for other users here 
UserPrincipal myself = UserPrincipal.Current; 

// get the manager for myself 
UserPrincipal myManager = GetManager(ctx, myself); 
3

上述GetManager的工作很好,除非没有管理员设置。轻微改变以适应这种情况:

// return manager for a given user 
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user) { 
    if (user != null) { 
     // get the DirectoryEntry behind the UserPrincipal object 
     var dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry; 

     if (dirEntryForUser != null) { 
      // check to see if we have a manager name - if so, grab it 
      if (dirEntryForUser.Properties["manager"] != null && dirEntryForUser.Properties["manager"].Count > 0) { 
       string managerDN = dirEntryForUser.Properties["manager"][0].ToString(); 
       // find the manager UserPrincipal via the managerDN 
       return UserPrincipal.FindByIdentity(ctx, managerDN); 
      } 
     } 
    } 
    return null; 
} 
0

这两个示例都正常工作。但我相信有改进的空间。

方法不应该检查参数是否为空,并返回null是一个坏习惯。另一方面,例外情况更为充分。

而不是要求上下文,应该可以从提供的UserPrincipal检索上下文,因此找到当前用户应该没有任何问题。

public static UserPrincipal GetManager(UserPrincipal user) 
{ 
    var userEntry = user.GetUnderlyingObject() as DirectoryEntry; 
    if (userEntry.Properties["manager"] != null 
    && userEntry.Properties["manager"].Count > 0) 
    { 
    string managerDN = userEntry.Properties["manager"][0].ToString(); 
    return UserPrincipal.FindByIdentity(user.Context,managerDN); 
    } 
    else 
    throw new UserHasNoManagerException(); 
} 

class UserHasNoManagerException : Exception 
{ }