2016-09-04 31 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 

希望幫助別人(我已經花了幾個小時拉我的頭髮)