I've been trying to build out basic auth tokens using powershell user persistent variables where I store the password as a secure string. This is what I have so far:
$PlainPassword = "atestpassword"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
[Environment]::SetEnvironmentVariable('JiraCreds', $SecurePassword, "User")
$cred = New-Object pscredential "TestUser", (ConvertTo-SecureString $env:JiraCreds)
$newPassword = $cred.Password
#NOTE: This returns 403 forbidden when making rest api calls with the basic auth token
$header = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("TestUser:$(ConvertFrom-SecureString $newPassword)"))}
#NOTE: Using this returns a 401 unauthorized when using this for get/post rest api calls with the basic auth token
$header = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("TestUser:$(ConvertFrom-SecureString $newPassword)"))}
The issue I’ve been running into all along is that I’m not sure how to adjust the code to properly translate the securestring in a way that builds the basic auth token correctly. One thing I noticed is that the actual/resulting basic auth tokens using the two methods above are much longer than what they should be and are not in the right token format compared to the following method:
$header = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("TestUser:atestpassword "))}
I’ve even tested the basic auth tokens in postman and they are failing there too.
NOTE: I have confirmed the json and the jira endpoint as well as method are working by testing with a basic auth method that does work in PowerShell.
Any help with this would be greatly appreciated.
To retrieve the plain-text password from a [pscredential]
instance, use .GetNetworkCredential().Password
:
$newPassword = $cred.GetNetworkCredential().Password
In the context of your command:
$header = @{
Authorization = 'Basic ' +
[Convert]::ToBase64String(
[Text.Encoding]::UTF8.GetBytes("$($cred.UserName):$newPassword")
)
}