c# - 无法使用 C# 和管理员用户设置密码和启用帐户
问题描述
使用WPF & C#,我可以设置 Active Directory 中的所有属性,但不能执行以下操作:
1)无法设置用户密码
2)无法启用用户
但是,我可以手动做同样的事情!
尝试的方法:
1.
DirectoryEntry directoryEntry=
directoryEntry.Invoke("SetPassword", new object[] {myPass@x6712}); // To set password
directoryEntry.Properties["userAcountControl"].Value=0x0200; //To Enable User
2.
DirectoryEntry uEntry = new DirectoryEntry(userDn);
uEntry.Invoke("SetPassword", new object[] { password });
uEntry.Properties["LockOutTime"].Value = 0; //unlock account
3.
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))
{
user.SetPassword( "newpassword" );
// or
user.ChangePassword( "oldPassword", "newpassword" );
user.Save();
}
}
密码设置错误:目标调用引发了异常。
ENABLE USER 错误:访问被拒绝。
注意:我使用的是域管理员用户。
该程序在上述这些行中给出了例外。
请指教!提前致谢 !!
解决方案
也许这只是您的问题中的一个错误,但是您在第一个示例中显示的代码无法编译,因为密码不在引号中。它应该是:
directoryEntry.Invoke("SetPassword", new object[] {"myPass@x6712"});
该代码调用IADsUser.SetPassword
. 文档中的“备注”指出了它工作的一些先决条件,即它必须是安全连接。因此,它可能无法建立安全连接。它通常会尝试使用 Kerberos 来执行此操作,因此那里可能出现了问题。
您可以尝试通过 LDAPS(基于 SSL 的 LDAP)将其指向端口 636 ( new DirectoryEntry("LDAP://example.com:636/CN=whatever,DC=example,DC=com")
) 进行专门连接,但这需要您信任所提供的证书。有时它是一个自签名证书,因此您需要将证书添加到运行它的任何计算机上的受信任证书中。
或者,您运行它的帐户没有该帐户的“重置密码”权限。
对于启用,该userAccountControl
属性是一个位标志,因此您不想将其设置为2
,主要是因为2
(或更准确地说,第二位)意味着它已被禁用。所以你想取消设置第二位。你会这样做:
directoryEntry.Properties["userAcountControl"].Value =
(int) directoryEntry.Properties["userAcountControl"].Value & ~2;
大多数情况下,这将导致512
( NORMAL_ACCOUNT
) 的值,但不一定。该帐户可能设置了您不想无意中取消设置的其他位。
您还需要调用.CommitChanges()
更改才能userAcountControl
生效:
directoryEntry.CommitChanges();
推荐阅读
- flutter - 在 Flutter 中显示多个视频
- javascript - 仅使用父 URL 的 3rd 方 cookie 检测
- c# - 复制和粘贴剪贴板 RTF C#
- reactjs - 无法使用 fetch 在 React 中执行 POST 操作
- mocking - 模拟 Java 11 HttpClient?
- vue.js - Vuetify Dark 主题存储在 cookie 和 localStorage 在 Nuxt SSR 中的 created() 钩子中不可用,我看到明暗主题之间闪烁
- python - 对于 mac 用户,os.startfile() 的替代方法是什么?
- python - Flask:在新会话开始时调用的函数
- r - 使用 R 中的日期变量对数据进行分类
- reactjs - React Native 中的 GetElementById 等效项