在我的应用程序中,我正在做用户可以从我的应用程序中控制他/她的本地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;
}
}
引发密码在下次登录时过期。重置标志
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;
}
}
检查是否设置了相关标志
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;
}
}
我正在使用WinNT来获取目录路径而不是LDAP。我使用以下方法来获取目录路径。
private String GetDirectoryPath()
{
String uName = this.userName;
String mName = this.userMachine;
String directoryPath = "WinNT://" + mName + "/" + uName;
return directoryPath;
}
我错过了什么吗?在这里帮帮我。
注意:首先,我使用 pwdLastSet 属性设置为 0(对于 on)和 -1(对于关闭),这会引发异常"在属性缓存中找不到目录属性",后来我发现 WinNT 不支持此属性,而是支持 PasswordExpire,它需要为 1 才能设置标志。这就是我所做的。
改用System.DirectoryServices.AccountManagement怎么样,在这种情况下,你可以调用以下代码:
UserPrincipal.Current.ExpirePasswordNow();
下面的代码应该可以工作:
de.Properties["pwdLastSet"][0] = 0;
从用户下次登录时必须更改密码(LDAP 提供程序):
若要强制用户在下次登录时更改其密码,请将 pwdLastSet 属性设置为零 (0)。若要删除此要求,请将 pwdLastSet 属性设置为 -1。属性不能设置为除系统之外的任何其他值。
我追踪到了这个。这对应于UserPrincipal.LastPasswordSet
属性。
该属性是只读的,因此您必须使用以下方法进行设置:
public bool UserMustChangePasswordNextLogon
{
get
{
return (_userPrincipal.LastPasswordSet == null);
}
set
{
if (value)
_userPrincipal.ExpirePasswordNow();
else
_userPrincipal.RefreshExpiredPassword();
}
}
就我而言,我将变量设置为在下次保存时过期或刷新密码,而不是在属性库中。
de.Properties["passwordExpired"][0] = 1; <br>
de.CommitChanges();