这确实是一个老问题,但就在最近我不得不从事一个类似的项目......如果有人遇到同样的问题,我会发布答案。
您找不到user
usingUserPrincipal
类的原因是,正如您提到的,您正在使用ContextType.Machine
. 但是在DirectEntry
课堂上你只是在做一个简单的LDAP://
查询。
这是我的解决方案。
我将服务器信息存储在.config
文件中。
...
//Server name and port
<add key ="ADLDS_Server" value="Servername:port"/>
//Note* depending on structure container will be different for everybody
<add key ="ADLDS_Container" value="CN=Some Value, DC=some value,DC=value"/>
...
然后我创建ADLDSUtility
了返回PrincipalContext
对象的类。
...
using System.DirectoryServices.AccountManagement
...
public class ADLDSUtility
{
public static ContextOptions ContextOptions = ContextOptions.SecureSocketLayer | ContextOptions.Negotiate;
public static PrincipalContext Principal
{
get
{
return new PrincipalContext(
ContextType.ApplicationDirectory,
ConfigurationManager.AppSettings["ADLDS_Server"],
ConfigurationManager.AppSettings["ADLDS_Container"],
//you can specify username and password if need to
ContextOptions);
}
}
从那里,我写了一个method
接受(用户名,currentPassword 和 newPassword)作为参数的。
public void ChangePassword(string userName, string currentPassword, string newPassword)
{
using (PrincipalContext ctx = ADLDSUtility.Principal)
{
using (UserPrincipal principal = new UserPrincipal(ctx))
{
using (var searchUser = UserPrincipal.FindByIdentity(ctx, IdentityType.UserPrincipalName, userName))
{
if (searchUser != null)
{
searchUser.ChangePassword(currentPassword, newPassword);
// searchUser.SetPassword(newPassword);
if (String.IsNullOrEmpty(searchUser.Guid.ToString()))
{
throw new Exception("Could not change password");
}
}
}
}
}
}
在此示例中,我通过 搜索用户UserPrincipalName
。但我们不限于此。我们还可以通过IdentityType.Guid
等搜索用户。
现在searchUser
有两种涉及密码的方法。我提供了他们两个。
//requires current and new password
searchUser.ChangePassword(currentPassword, newPassword);
//setting a password. Only requires new password.
searchUser.SetPassword(newPassword);
注意最好使用 SSL 设置或更改密码。*