Picking up PowerShell into my repertoire and was attempting to recreate a simple action that I do in Python's requests module.
For reference, an application I regularly interact with returns a cookie within a response when a POST call is made using a username and password. Below is a Python function I use to capture the cookie jar and use on subsequent calls:
def getSessionToken(baseURL, username, password, certificate):
session_url = baseURL + "/session"
session_headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
}
session_data = '{ "username": "%s", "password": "%s" }' % (username, password)
try:
session = requests.post(session_url, headers=session_headers, data=session_data, verify=certificate)
session.raise_for_status()
except requests.exceptions.HTTPError as err:
raise SystemExit(err)
return session.cookies
I have something currently working, I receive a 200 and I get a token in JSON format, but I don't know how to capture the cookie itself.
$SessionUrl = 'https://someaddress.com/api/session'
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("accept", "application/json")
$headers.Add("Content-Type", "application/json")
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$sessionBody = "{ `"username`": `"Hello`", `"password`": `"StackOverflow!`" }"
$response = Invoke-RestMethod -Method 'POST' -Headers $headers -Body $sessionBody -Uri $SessionUrl -SessionVariable mySession
$cookies = $mySession.cookies.GetCookies($SessionUrl)
$session.Cookies.Add($cookies)
$somedata = Invoke-RestMethod -Method 'GET' -Headers $headers -Uri 'https://someaddress.com/api/v2/somedata?skip=0&limit=10' -SessionVariable $session
$somedata | ConvertTo-Json
Write-Output "All done"
I reviewed this question, this question, and this question and have revised my own question about five times. The good news is that I now see a four length array in $cookies with the cookie data I need but I'm not sure how to format it in such a way that I can pass it into the second GET.