jch*_*ury 2 c# active-directory
在我的应用程序中,我正在做的事情是用户可以通过我的应用程序控制他/她的本地Windows用户帐户,即可以从我的应用程序中创建用户,设置/删除密码,更改密码以及调用密码到期策略。现在,在这一点上,我需要弄清楚如果用户要在下次登录时更改密码,那么会发生什么。正如许多论坛和博客所说的那样,我做了相应的编码:
下次登录时调用密码过期
public bool InvokePasswordExpiredPolicy()
{
try
{
string path = GetDirectoryPath();
string attribute = "PasswordExpired";
DirectoryEntry de = new DirectoryEntry(path);
de.RefreshCache(new string[] { attribute });
if(de.Properties.Contains("PasswordExpired"))
de.Properties[attribute].Value = 1;
de.CommitChanges();
return true;
}
catch (Exception)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
在下次登录时提示密码过期。重置标志
public bool ProvokePasswordExpiredPolicy()
{
try
{
string path = GetDirectoryPath();
string attribute = "PasswordExpired";
DirectoryEntry de = new DirectoryEntry(path);
de.RefreshCache(new string[] { attribute });
de.Properties[attribute].Value = -1;
de.CommitChanges();
return true;
}
catch (Exception)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
检查是否设置了相关标志
public bool isPasswordPolicyInvoked()
{
try
{
string path = GetDirectoryPath();
string attribute = "PasswordExpired";
DirectoryEntry de = new DirectoryEntry(path);
de.RefreshCache(new string[] { attribute });
int value = Convert.ToInt32(de.Properties[attribute].Value);
if (value == 1)
return true;
else
return false;
}
catch (Exception)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用WinNT来获取目录路径而不是LDAP。我使用以下方法获取目录路径。
private String GetDirectoryPath()
{
String uName = this.userName;
String mName = this.userMachine;
String directoryPath = "WinNT://" + mName + "/" + uName;
return directoryPath;
}
Run Code Online (Sandbox Code Playgroud)
有什么我想念的吗?帮帮我
注意:首先,我使用pwdLastSet属性设置为0(表示on)和-1(表示off),这会引发异常“ Property Cache中找不到目录属性”,后来我发现WinNT不支持此属性。它支持PasswordExpired,设置该标志需要为1。那就是我所做的。
下面的代码应该工作:
de.Properties["pwdLastSet"][0] = 0;
Run Code Online (Sandbox Code Playgroud)
要强制用户在下次登录时更改其密码,请将 pwdLastSet 属性设置为零 (0)。要取消此要求,请将 pwdLastSet 属性设置为 -1。除系统外,pwdLastSet 属性不能设置为任何其他值。
如何改用System.DirectoryServices.AccountManagement,在这种情况下,您可以调用以下代码:
UserPrincipal.Current.ExpirePasswordNow();
Run Code Online (Sandbox Code Playgroud)