Ad login test authentication

From UVOO Tech Wiki
Jump to navigation Jump to search

https://itpro-tips.com/2019/test-ad-authentication-via-powershell/

Be careful not to test authentications loop with a bad password, otherwise it may cause a lockout of the AD account.

PowerShell allows you to test login / password authentication against Active Directory using one of these two methods:

$UserName = 'xxxx'
$Password = 'yyyy'
Function Test-ADAuthentication {
    param(
        $username,
        $password)

    (New-Object DirectoryServices.DirectoryEntry "",$username,$password).psbase.name -ne $null
}
Test-ADAuthentication -username $UserName -password $password

or an advanced function if you need to test against another AD domain:

function Test-ADAuthentication {
    Param(
        [Parameter(Mandatory)]
        [string]$User,
        [Parameter(Mandatory)]
        $Password,
        [Parameter(Mandatory = $false)]
        $Server,
        [Parameter(Mandatory = $false)]
        [string]$Domain = $env:USERDOMAIN
    )

    Add-Type -AssemblyName System.DirectoryServices.AccountManagement

    $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain

    $argumentList = New-Object -TypeName "System.Collections.ArrayList"
    $null = $argumentList.Add($contextType)
    $null = $argumentList.Add($Domain)
    if($null -ne $Server){
        $argumentList.Add($Server)
    }

    $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $argumentList -ErrorAction SilentlyContinue
    if ($null -eq $principalContext) {
        Write-Warning "$Domain\$User - AD Authentication failed"
    }

    if ($principalContext.ValidateCredentials($User, $Password)) {
        Write-Host -ForegroundColor green "$Domain\$User - AD Authentication OK"
    }
    else {
        Write-Warning "$Domain\$User - AD Authentication failed"
    }
}
#Test-ADAuthentication -User toto -Password passXX
#Test-ADAuthentication -User toto -Password passXX -Server xxx.domain.com
The return values are:

TRUE if authentication is successful
FALSE if authentication failed. The reason can be:
bad login. Test if AD user exists
bad password
locked out AD acount: Get-ADUser -Identity xxx -Properties LockedOut,AccountLockoutTime | Select samaccountname,LockedOut,AccountLockoutTime
disabled AD account: Get-ADUser -Identity xxxx | Select samaccountname,Enabled