[英]How to search in multiple domains using System.DirectoryServices.AccountManagement?
[英]User created using using System.DirectoryServices.AccountManagement unable to access Sharepoint site
相關代碼:-這是一個正在進行的工作,我仍處於發現階段,因此並非所有異常路徑都完整。 不必擔心重新拋出異常-我會解決的。
我還必須說,我對AD的經驗很少。 我從來沒有真正想到過它。
大多數代碼來自Microsoft示例。
public static bool AddUser(string firstName, string lastName, string userLogonName,
string employeeID, string emailAddress, string telephone, string address,
string Password, DateTime expiry)
{
PrincipalContext principalContext = GetContext();
// Check if user object already exists in the store
if (UserExists(userLogonName))
{
throw new Exception(userLogonName + " already exists. Please use a different User Logon Name.");
}
// Create the new UserPrincipal object
UserPrincipal userPrincipal = new UserPrincipal(principalContext);
if (lastName != null && lastName.Length > 0)
{
userPrincipal.Surname = lastName;
}
if (firstName != null && firstName.Length > 0)
{
userPrincipal.GivenName = firstName;
}
if (employeeID != null && employeeID.Length > 0)
{
userPrincipal.EmployeeId = employeeID;
}
if (emailAddress != null && emailAddress.Length > 0)
{
userPrincipal.EmailAddress = emailAddress;
}
if (telephone != null && telephone.Length > 0)
{
userPrincipal.VoiceTelephoneNumber = telephone;
}
if (userLogonName != null && userLogonName.Length > 0)
{
userPrincipal.SamAccountName = userLogonName;
}
userPrincipal.AccountExpirationDate = expiry;
userPrincipal.SetPassword(Password);
userPrincipal.Enabled = true;
userPrincipal.PasswordNeverExpires = true;
try
{
userPrincipal.Save();
}
catch (Exception e)
{
throw new Exception("Exception saving user object. ", e);
}
return true;
}
和
public static void AddUserToGroup(string userLogonName, string groupName)
{
try
{
using (PrincipalContext principalContext = GetContext())
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, groupName);
group.Members.Add(FindUser(userLogonName));
group.Save();
}
}
catch (System.DirectoryServices.DirectoryServicesCOMException e)
{
throw e;
}
}
當我運行測試(添加用戶)並檢查Active Directory時,該用戶在那里。 到現在為止還挺好。
然后,我運行添加到組測試,用戶在AD中顯示為MemberOf組。 同樣,一切都如預期。
現在,我導航到Sharepoint站點,然后嘗試以新創建的用戶身份登錄。 我收到“對不起,該站點尚未與您共享。”
...插曲:組和權限的大量嘲弄無濟於事...
接下來,我在AD中手動創建了一個用戶,然后運行“添加到組”測試。 在AD中一切看起來都不錯,我可以成功登錄到Sharepoint網站。
因此,我懷疑AddUser方法有問題,但是我無法弄清楚是什么。 我看不到以編程方式創建的用戶和手動創建的用戶之間的區別。
如我們的評論中所述,在測試之前,請等待更長的時間將所做的更改復制到所有域控制器。
根據GetContext()
方法的編寫方式,您甚至可能在創建帳戶時遇到復制問題。 如果它每次都創建一個新的PrincipalContext
對象,則理論上它可以第二次連接到另一個DC,此時該新帳戶還不存在。 (盡管它會嘗試將您與最近的人聯系起來,所以可能始終是同一個人)
為了避免獲得不同DC的任何機會,您可以重用相同的PrincipalContext
對象,或者可以讀取PrincipalContext
的ConnectedServer
屬性,該屬性將告訴您最終使用了哪個DC。 然后,您可以在以后使用它來確保在同一DC上進行所有更改。
如果要定位到特定的DC,則PrincipalContext
的構造函數將允許您傳遞特定的DC作為域名:
var context = new PrincipalContext(ContextType.Domain, "dc1.domain.com");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.