#PSTip Validate Active Directory Credentials

Note: This tip requires PowerShell 2.0 or later.

PowerShell let’s you tap into .NET Framework and do all kind of poking. Recently, while reading up this article on CodeProject  came across the ValidateCredentials() method on the PrincipalContext class instance.

Below is how you use this nifty little trick in PowerShell to validate AD creds for a user (One can use this for local machine too):

# add type to allow validating credentials
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

# Create the Domain Context for authentication
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain

# We specify Negotiate as the Context option as it takes care of choosing the best authentication mechanism i.e. Kerberos or NTLM (non-domain joined machines).
$ContextOptions = [System.DirectoryServices.AccountManagement.ContextOptions]::Negotiate

Let’s create the instance of the PrinicipalContext class by using one of the Constructor . Note this requires a DC name to be passed. Don’t worry if you don’t know the DC name, we can easily use the $env:USERDNSDOMAIN environment variable and it takes care of it.

$PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType, $env:USERDNSDOMAIN)

Before it is time to execute the method, let’s see the method definition

PS> $PrincipalContext.ValidateCredentials
OverloadDefinitions
-------------------
bool ValidateCredentials(string userName, string password)
bool ValidateCredentials(string userName, string password, System.DirectoryServices.AccountManagement.ContextOptions options)

We use the second method definition now to validate the user credential, and we can store the user credentials in a credential object (for ease) here.

PS> $Cred = Get-Credential
PS> $PrincipalContext.ValidateCredentials($cred.UserName, $cred.GetNetworkCredential().password, $ContextOptions)
True

PS># Et Voila !

About the author: Deepak Dhami

Deepak (aka DexterPOSH) is a PowerShell Enthusiast and an active member of PowerShell Bangalore and Hyderabad User Groups. He blogs at http://dexterposh.blogspot.com and you can follow him on Twitter @DexterPOSH.

Related Posts

%d bloggers like this: