EDIT:
I am trying to read a token value from a text file to build a header that can be used for a REST API call.
If I request a temporary token using a credential (option T) the subsequent REST method works but if I read the permanent token in from text file (option P) on the local file system the method that worked before with the temp token fails.
ERROR: Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send. Invoke-Test.ps1 (41, 13): ERROR: At Line: 41 char: 13 ERROR: + $response = Invoke-RestMethod -Method Get -Headers $headers -Uri "$ap ... ERROR: +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ERROR: + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException ERROR: + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Code:
# Allow the use of self-signed SSL certificates, TLS
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$server = "https://192.168.1.1"
$app_rest = "$server/api/v1"
$choice = Read-Host "Enter T or P"
If($choice -eq "T") {
Write-Host "Try and obtain temp token"
$Username = Read-Host "Enter Username"
$Password = Read-Host "Enter Password" -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$creds = @{
username = $Username
password = $Password
grant_type = "password"
};
$response = Invoke-RestMethod -Method Post -Uri "$server/api/token" -Body $creds
$token = $response.access_token
Write-Host $token
}
ElseIf($choice = "P") {
Write-Host "Try and use perm token"
#$token = [IO.File]::ReadAllText("C:\temp\SBXtoken.txt")
$token = Get-Content "C:\temp\SBXtoken.txt" -Raw
Write-Host $token
}
Else {Break;}
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $token")
$response = Invoke-RestMethod -Method Get -Headers $headers -Uri "$app_rest/status"
$status = $response.status;
Write-Host $status