2016-09-04 103 views
1

我试图访问基于Swagger的API使用powershell invoke-restmethod与websession(希望)捕获饼干/会话信息我需要做一个后期的方法。 我开始通过请求CSRFPowerShell的Invoke-RestMethod缺少cookie值

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

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

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

由于缺少cookie值而失败。如果我通过Firefox做了一个正常的请求,我会看到带有jsessionid等的cookie,但我不知道如何让这些值在我可以使用它们的地方(请原谅我在这里无知 - 我对于invoke-restmethod在PS)

+0

第一次调用时,SessionVariable中缺少$值吗?应该是:$ webSession,根据文档:“指定一个web请求会话。输入变量名称,包括美元符号($)”https://technet.microsoft.com/en-us/library/hh849971.aspx –

+0

@DavidBrabant - 感谢大卫 - 如果你从会话中产生会话,我不相信你需要会话变量中的$ - 从你提供的链接 - “创建一个web请求会话,输入一个变量名称(没有一美元Invoke-RestMethod命令的SessionVariable参数的值,Invoke-RestMethod创建会话并将其保存在变量中,在随后的命令中,使用该变量作为WebSession参数的值。 – AskJarv

回答

3

我sussed出来(在最后所很痛苦) - 我不得不建立自己的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 

希望帮助别人(我已经花了几个小时拉我的头发)