編輯:改變後的認證流程,現在收到錯誤:調用-RestMethod:基礎連接已關閉:上一個發送發生意外的錯誤
我想從一個文本文件中讀取一個令牌值建立一個可用於REST API調用的頭文件。
如果我使用憑證請求臨時令牌(選項T),後續的REST方法可以工作,但是如果我從本地文件系統的文本文件(選項P)中讀取永久令牌,則使用temp令牌失敗。
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
代碼:
# 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
在這裏完全損失。如果我總是通過從If語句中取出這些行來運行第一個irm,並且始終運行它們,那麼所有後續的irm都可以工作。 – dross