开发者

Setting the LastPasswordSet date for a user in Active Directory

I want to set the LastPasswordSet attribute of a user in Microsoft Active Directory.

The .NET UserPrincipal API exposes the LastPasswordSet property as readonly.

Is there a way around this, to set the value (perhaps using ADSI)?

Edit:

MSDN provides the following example code:

usr.Properties["pwdLastSet"].Value = -1; // To turn on, set this value to 0.
usr.CommitChanges();

This forces the 开发者_StackOverflow社区user to change their password at next logon. I presume if I replace -1 with a date-time in the relevant format, this will do what I want.

It does not, however, show how I get hold of the principal (presumably usr). I'll upvote anything that helps me find this out.


Another way would be to perform a search against the AD through the DirectorySearcher class using the login of your users.

public DirectoryEntry GetUser(string domain, string loginName) {
    DirectorySearcher ds = new DirectorySearcher();
    ds.SearchRoot = new DirectoryEntry(domain);
    ds.SearchScope = SearchScope.Subtree;
    ds.PropertiesToLoad.Add("sAMAccountName");
    ds.PropertiesToLoad.Add("pwdLastSet");
    ds.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0})", loginName);

    SearchResult sr = null;

    try {
        sr = ds.FindOne();
        if (sr == null) return null;
        return sr.GetDirectoryEntry();
    } catch (Exception) {
        throw;
    }
}

Then, when wanting to set your PasswordLastSet property, you assure that the user exists and that there is no spelling mistakes.

string loginName = "AstonB1";

using(DirectoryEntry user = GetUser(loginName)) {
    if (user == null) return;

    user.Properties["pwdLastSet"].Value = whatever-format-the-date-should-be;
    user.CommitChanges();
    user.Close();
}


Something like this?

var usr = new DirectoryEntry("LDAP://CN=Old User,CN=users,DC=fabrikam,DC=com");
usr.Properties["pwdLastSet"].Value = whatever-format-the-date-should-be;
usr.CommitChanges();

As yet untested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜