怎么样找服务器用户,如何在远程LDAP服务器上的特定OU中搜索用户?

这真是一个老问题,但就在最近,我不得不对类似的项目工作...如果有人跑进了同样的问题,我会发布了答案。

使用UserPrincipal类找不到user的原因是,正如您所提到的,您正在使用ContextType.Machine进行搜索。但在DirectEntry类中,您只是在执行简单的LDAP://查询。

这是我的解决方案。

我将我的服务器信息存储在.config文件中。

...

//Server name and port

//Note* depending on structure container will be different for everybody

...

我然后创建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)为PARAMATERS。

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来设置或更改密码。*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值