Powershell Invoke-RestMethod 缺少 cookie 值

Powershell Invoke-RestMethod missing cookie values

我正在尝试使用带有 websession 的 powershell invoke-restmethod 访问基于 Swagger 的 API 以(希望)捕获 cookies/session 我需要做 post 的信息方法。 我首先请求 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

希望能对其他人有所帮助(我为此费了好几个小时!)