如何在用户密码过期或"用户必须在下次登录时更改密码"时检查AD用户凭据

Mon*_*ica 3 .net authentication active-directory

我想知道是否有任何.Net方法来验证Active Directory用户凭据,即使用户的密码已过期或用户具有"用户必须在下次登录时更改密码"设置.我尝试了PrincipalContext.ValidateCredential,这为我的用户返回false.我也尝试过Ldap Bind,但这也不起作用.我的目的是验证用户身份,然后如果密码过期或者他必须在下次登录时更改密码,则使用更改密码对话框提示他.

Ped*_*dro 7

我们的设置中有几个AD控制器,并且PrincipalContext.ValidateCredentials方法在用户的Windows 2003服务器上的AD控制器上始终返回false,并选中"用户必须在下次登录时更改密码"复选框.

但是对于Windows 2008 R2服务器上的那些,即使选中了复选框,如果信用证有效,它也会返回true.

所以我只是确保我的代码击中了一个Windows 2008 R2服务器并且这样做了.

我确实在研究2003服务器的解决方案(之前我意识到事情只适用于其他服务器).这是代码:

var adContext = new PrincipalContext(ContextType.Domain, adLocation, adContainer, adAdminUsername, adAdminPassword);

var initialValidation = adContext.ValidateCredentials(username, password);
Console.WriteLine("Initial validation returned: " + initialValidation);

if (!initialValidation)
{
    // maybe validation failed because "user must change password at next logon".
    // let's see if that is the case.

    var user = UserPrincipal.FindByIdentity(adContext, username);
    if (user.LastPasswordSet == null)
    {
        // the user must change his password at next logon. So this might be
        // why validation returned false

        // uncheck the "change password" checkbox and attempt validation again

        var deUser = user.GetUnderlyingObject() as DirectoryEntry;
        var property = deUser.Properties["pwdLastSet"];
        property.Value = -1;
        deUser.CommitChanges();

        // property was unset, retry validation
        adContext.ValidateCredentials(username, password);
        Console.WriteLine("Secondary validation returned: " + adContext.ValidateCredentials(username, password));

        // re check the checkbox
        property.Value = 0;
        deUser.CommitChanges();
  }
}
Run Code Online (Sandbox Code Playgroud)