#PSTip Validating Active Directory user credentials

Note: This tip requires PowerShell 2.0 or above.

There are times when you need to validate the credentials of an Active Directory user account. A typical scenario is when you have a service object that no one remembers its credentials and you don’t want to reset it before you make sure you tried all the passwords the object may has.

One option would be to try and log on to the server using those credentials. However, you can’t use that if you want to automate the process. In this case you’d want to check the PrincipalContext.ValidateCredentials method.

The ValidateCredentials method returns a Boolean value that specifies whether the specified username and password are valid. To use that method we first need to load the System.DirectoryServices.AccountManagement assembly (part of .NET 3.5). We create a ContextType object, pass it together with the user domain name to the PrincipalContext object, and then invoke the method.

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$Domain = $env:USERDOMAIN

$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$Domain
Filed in: Columns, Tips and Tricks Tags: , , , ,

11 Responses to "#PSTip Validating Active Directory user credentials"

  1. Sebastian N. says:

    Does the verification count as login attempt?

  2. karank says:

    Same question – does the verification count as a login attempt?

  3. ShayLevy says:

    Good question. I don’t know for sure, but you can easily check it.

    Using a test account, make a few failed login attempts and check the user’s BadPwdCount active directory property, see if it adds up. Another way would be to check the last time a failed login was captured by querying the badPasswordTime property.

    Queries must be performed against all DCs. Another way would be to simply supply wrong credentials more times than the ‘Account Lockout threshold’ allows and then check if the user can still log in.

  4. Sid says:

    Got this error. Using powershell 3.0

    Exception calling “ValidateCredentials” with “2” argument(s): “The server cannot handle directory requests.”
    At line:9 char:1
    + $pc.ValidateCredentials($UserName,$Password)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DirectoryOperationException

    • zls says:

      I am getting the same error as you and I am using Powershell DSC to set an ADUser. Did you find out what was causing this error?

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: