首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell Invoke-RestMethod缺少Cookie值

Powershell Invoke-RestMethod缺少Cookie值
EN

Stack Overflow用户
提问于 2016-09-05 03:15:46
回答 1查看 7K关注 0票数 4

我正在尝试使用powershell invoke-restmethod和websession来访问基于Swagger的API,以便(希望)捕获执行post方法所需的cookie/会话信息。我首先请求一个CSRF

代码语言:javascript
复制
$CSRF = Invoke-RestMethod -Uri ($Uri+'csrf-token') -Method Get -Credential $Creds -ContentType 'application/json'-SessionVariable websession

我可以看到正确的标记值,没有任何问题。查看websession变量,我确实有一些数据,但我根本没有得到任何cookie值。因此,如果我使用会话变量提交第二个请求:

代码语言:javascript
复制
Invoke-RestMethod -Method Post -Uri ($Uri+'post') -Headers $Header -Body $Body -Credential $creds -WebSession $websession

由于缺少Cookie值而失败。如果我通过Firefox执行一个普通的请求,我会看到带有jsessionid的cookie,等等,但是我不知道如何将这些值获取到我可以使用它们的地方(请原谅我在这里的无知-我对PS中的invoke-restmethod还比较陌生)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-06 01:58:09

我已经弄清楚了(最后--非常痛苦)--我不得不构建自己的cookie:

代码语言:javascript
复制
$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

希望这对其他人有帮助(我已经花了几个小时来解决这个问题了!)

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39320581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档