It would be great if there was a way to pass a PSCredential with a $null username to the web cmdlets. I ran into this with an API that has no username, just a API key that is used for basic auth.
Steps to reproduce
$TestCreds = Get-Credential
if ($TestCreds.UserName) {
$TestCreds = New-Object System.Management.Automation.PSCredential -ArgumentList (
[pscustomobject] @{
UserName = $null
Password = $TestCreds.Password
}
)
}
Invoke-RestMethod -Uri 'https://httpbin.org/headers' `
-Authentication Basic `
-Credential $TestCreds
Expected behavior
$TestCreds = Get-Credential
if ($TestCreds.UserName) {
$TestCreds = New-Object System.Management.Automation.PSCredential -ArgumentList (
[pscustomobject] @{
UserName = ' '
Password = $TestCreds.Password
}
)
}
Invoke-RestMethod -Uri 'https://httpbin.org/headers' `
-Authentication Basic `
-Credential $TestCreds
There is a workaround where you pass a username with a single space. The space is base64 encoded however. So, in the example below, I passed 'username' and 'password' as the creds. You'll notice that 'IDpwYXNzd29yZA==' was passed in the basic auth header, which decodes to ' :password' (note the leading space).
PowerShell credential request
Enter your credentials.
User: username
Password for user username: ********
headers
-------
@{Authorization=Basic IDpwYXNzd29yZA==; Host=httpbin.org; User-Agent=Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.17134; en-US) PowerShell/6.1.2}
Actual behavior
Invoke-RestMethod : Object reference not set to an instance of an object.
At C:\Users\bdavis\Documents\Scripts\temp_01.ps1:12 char:1
+ Invoke-RestMethod -Uri 'https://httpbin.org/headers' `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-RestMethod], NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Environment data
Name Value
---- -----
PSVersion 6.1.2
PSEdition Core
GitCommitId 6.1.2
OS Microsoft Windows 10.0.17134
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
It would be great if there was a way to pass a PSCredential with a $null username to the web cmdlets. I ran into this with an API that has no username, just a API key that is used for basic auth.
Steps to reproduce
Expected behavior
There is a workaround where you pass a username with a single space. The space is base64 encoded however. So, in the example below, I passed 'username' and 'password' as the creds. You'll notice that 'IDpwYXNzd29yZA==' was passed in the basic auth header, which decodes to ' :password' (note the leading space).
Actual behavior
Environment data