2011-01-26 78 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 
{ }