[英]Powershell Invoke-RestMethod missing cookie values
我正在嘗試使用帶有websession的powershell invoke-restmethod訪問基於Swagger的API,以(希望)捕獲我需要執行post方法的cookie /會話信息。 我首先請求CSRF
$CSRF = Invoke-RestMethod -Uri ($Uri+'csrf-token') -Method Get -Credential $Creds -ContentType 'application/json'-SessionVariable websession
而且我可以看到正確的令牌值,沒有任何問題。 查看websession變量,我確實有一些數據,但是我根本沒有任何cookie值。 因此,如果我使用會話變量提交第二個請求:
Invoke-RestMethod -Method Post -Uri ($Uri+'post') -Headers $Header -Body $Body -Credential $creds -WebSession $websession
由於缺少cookie值而失敗。 如果我通過Firefox發出普通請求,則會看到帶有jsessionid的cookie,等等,但我不知道如何在可以使用它們的地方獲取這些值(請原諒我的無知-我對invoke-restmethod還是比較陌生在PS中)
我已經解決了(最后-非常痛苦)-我必須構建自己的cookie:
$CSRF = Invoke-RestMethod -Uri ($Uri+'csrf-token') -Method Get -Credential $Creds -ContentType 'application/json' -SessionVariable websession -MaximumRedirection 0
$CSRFToken = $CSRF.tokenValue
# Capture cookie
$cookiejar = New-Object System.Net.CookieContainer
$cookieUrl = $uri +'csrf-token'
$cookieheader = ""
$webrequest = [System.Net.HTTPWebRequest]::Create($cookieUrl);
$webrequest.Credentials = $creds
$webrequest.CookieContainer = $cookiejar
$response = $webrequest.GetResponse()
$cookies = $cookiejar.GetCookies($cookieUrl)
# add cookie to websession
foreach ($cookie in $cookies) {$websession.Cookies.Add((Create-Cookie -name $($cookie.name) -value $($cookie.value) -domain $apiserverhost))}
# Finally, I can post:
Invoke-RestMethod -Method Post -Uri ($Uri+'versions/createVersionRequests') -Headers $Header -Body $Body -Credential $creds -WebSession $websession
希望能對其他人有所幫助(為此,我花了數小時來拉頭發!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.