4
votes

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)

1
Missing $ in your SessionVariable in the first call? Should be: $webSession, according to documentation: "Specifies a web request session. Enter the variable name, including the dollar sign ($)" technet.microsoft.com/en-us/library/hh849971.aspxDavid Brabant
@DavidBrabant - Thanks David - I don't believe you need the $ in the sessionvariable if you're generating it from that session - from the link you provided - "To create a web request session, enter a variable name (without a dollar sign) in the value of the SessionVariable parameter of an Invoke-RestMethod command. Invoke-RestMethod creates the session and saves it in the variable. In subsequent commands, use the variable as the value of the WebSession parameter."AskJarv

1 Answers

6
votes

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!)