简体   繁体   中英

Powershell Invoke-RestMethod missing cookie values

I'm trying to access a Swagger based API using powershell invoke-restmethod with websession to (hopefully) capture the cookies/session information I'd need to do a post method. I start by requesting a CSRF

$CSRF = Invoke-RestMethod -Uri ($Uri+'csrf-token') -Method Get -Credential $Creds -ContentType 'application/json'-SessionVariable websession

and I can see the correct token value without any issues. Looking at the websession variable I do have some data, but I don't get any cookie values at all. Thus if I submit a second request using the session variable:

Invoke-RestMethod -Method Post -Uri ($Uri+'post') -Headers $Header -Body $Body -Credential $creds -WebSession $websession

it fails due to the missing cookie values. If I do a normal request via Firefox I see cookies with a jsessionid, etc but I don't know how to get these values somewhere where I can use them (please excuse me ignorance here- I'm relatively new to the invoke-restmethod in PS)

I've sussed it out (at last- very painful) - I had to build my own 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

Hope that helps someone else (I've spent hours pulling my hair out over this!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM