你想讓用戶改變他們自己的密碼,或者管理員要重置它嗎?
您是否收到任何輸入內容,或者當您調用FindOne時發生錯誤?
這是我使用的代碼,「模仿者」是允許冒充域管理員帳戶以確保適當權限的類。你應該能夠找到它here。
public ServiceResponse ChangePassword(string username, string oldPassword, string newPassword)
{
ServiceResponse response = new ServiceResponse();
try
{
var entry = new DirectoryEntry(DomainUsersConnectionString, username, oldPassword);
var nativeObject = entry.NativeObject;
// Check passed. Can reset the password now
entry = RootDirectoryEntry;
var user = FindUserInDirectoryEntry(username, entry);
response = SetPassword(user, newPassword);
user.Close();
}
catch (DirectoryServicesCOMException ex)
{
response.Status = Status.Error;
response.Message = ex.ExtendedErrorMessage;
m_Logger.Error("Failed to change password for user {0}: {1} - {2}", username, ex.ExtendedErrorMessage, (ex.InnerException ?? ex));
}
catch (Exception ex)
{
response.Status = Status.Error;
response.Message = ex.Message;
m_Logger.Error("Failed to change password for user {0}: {1} -{2}", username, ex.Message, (ex.InnerException ?? ex));
}
return response;
}
/// <summary>
/// Finds the user in directory entry.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="dirEntry">The dir entry.</param>
/// <returns></returns>
protected static DirectoryEntry FindUserInDirectoryEntry(string username, DirectoryEntry dirEntry)
{
// rip off Domain name if username contains it
string domainName = String.Format(@"{0}\", DomainName).ToLowerInvariant();
username = username.Replace(domainName, "");
DirectorySearcher searcher = new DirectorySearcher(dirEntry)
{
Filter = String.Format("(samAccountName={0})", username)
};
var searchResult = searcher.FindOne();
if (searchResult != null)
{
DirectoryEntry user = searchResult.GetDirectoryEntry();
return user;
}
return null;
}
private ServiceResponse SetPassword(DirectoryEntry user, string password)
{
ServiceResponse response = new ServiceResponse();
try
{
using (var impersonator = new Impersonator(DomainAdminUsername, DomainName, DomainAdminPassword))
{
user.Invoke("SetPassword", new object[] { password });
user.Properties["LockOutTime"].Value = 0; //unlock account
user.CommitChanges();
}
response.Status = Status.Success;
}
catch (DirectoryServicesCOMException ex)
{
response.Status = Status.Error;
response.Message = ex.ExtendedErrorMessage;
m_Logger.Error("SetPassword failed for user {0}: {1}", user.Name, ex.ExtendedErrorMessage);
}
catch (Exception ex)
{
response.Status = Status.Error;
response.Message = ex.Message;
m_Logger.Error("SetPassword failed for user {0} by {1} at {2}: {3}: {4}", user.Name,
DomainAdminUsername, DomainName,
ex.Message, (ex.InnerException ?? ex).ToString());
}
return response;
}
注意事項可能會影響你:
如果存在
檢索「NativeObject」似乎對緩存的作用
- 刪除域名/連接
- 這是使用「SetPassword」這需要"Reset Password extended control access right"
謝謝羅傑。我需要用戶能夠更改自己的密碼,最好不需要任何第三方課程。這可能嗎?我的印象是這樣的。 – sarsnake
是的,您應該能夠放棄Impersonator(無論如何可以自由使用的源代碼)並交換到ChangePassword而不是SetPassword。主要問題應該是:什麼是例外?它可能是您聲明/分配條目的位置,或者您調用ChangePassword的位置 –