I am invoking a web api which uses ntlm authentication from PowerShell. Script gets user credentials using get-credential. it works fine. code is below.
$cred_getcred_approach= get-credential
$response = Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -Credential $cred_getcred_approach
to avoid the credential prompt I created a PSCredential object with same userid & password(that I filled in the get-credential prompt)
$User = "Domain01\User01"
$PWord = ConvertTo-SecureString -String "P@sSwOrd" -AsPlainText -Force
$cred_createcred_approach = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Authentication fails in this case. Surprised with this behavior, I exported both PSCredential objects to an xml file using below code.
$cred_getcred_approach | Export-CliXml -Path "c:\path\cred_getcred_approach.xml"
$cred_createcred_approach | Export-CliXml -Path "c:\path\cred_createcred_approach.xml"
and the password value doesn't match between these 2 xml files. I tried to import the xml files and invoke the web api.
$cred_getcred_approach= Import-CliXml -Path "c:\path\cred_getcred_approach.xml"
$cred_createcred_approach= Import-CliXml -Path "c:\path\cred_createcred_approach.xml"
As expected, the authentication was successful when I imported in the first case.(from the xml(cred_getcred_approach.xml) which was exported from the get-credential PSCredential object and failed on other case. What can be the reason? is there any difference in the secure string algorithms? Is there any ways to fix this?
Update
secured string was problematic. below code fixed it.
$pass = ConvertTo-SecureString -AsPlainText "P@sSwOrd" -Force
I got the original problematic code one from the microsoft documentation. below is that problematic code.
$pass = ConvertTo-SecureString -String "P@sSwOrd" -AsPlainText -Force
Thanks to @tomalak for the pointer.
Invoke-WebRequest -UseDefaultCredentialsto use integrated authentication, i.e. to use the credential of the account running the script. This way you don't have to rely on obtaining or saving any explicit credentials at all. - Tomalak