简体   繁体   English

Powershell Invoke-RestMethod缺少Cookie值

[英]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. 我正在尝试使用带有websession的powershell invoke-restmethod访问基于Swagger的API,以(希望)捕获我需要执行post方法的cookie /会话信息。 I start by requesting a CSRF 我首先请求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. 查看websession变量,我确实有一些数据,但是我根本没有任何cookie值。 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. 由于缺少cookie值而失败。 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) 如果我通过Firefox发出普通请求,则会看到带有jsessionid的cookie,等等,但我不知道如何在可以使用它们的地方获取这些值(请原谅我的无知-我对invoke-restmethod还是比较陌生在PS中)

I've sussed it out (at last- very painful) - I had to build my own cookie: 我已经解决了(最后-非常痛苦)-我必须构建自己的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!) 希望能对其他人有所帮助(为此,我花了数小时来拉头发!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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