rest - Powershell Invoke-RestMethod 缺少 cookie 值

标签 rest powershell swagger

我正在尝试使用带有 websession 的 powershell invoke-restmethod 访问基于 Swagger 的 API,以(希望)捕获我需要执行 post 方法的 cookie/ session 信息。
我首先请求 CSRF

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

我可以毫无问题地看到正确的 token 值。查看 websession 变量,我确实有一些数据,但我根本没有得到任何 cookie 值。因此,如果我使用 session 变量提交第二个请求:
Invoke-RestMethod -Method Post -Uri ($Uri+'post') -Headers $Header -Body $Body -Credential $creds -WebSession $websession

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

最佳答案

我已经解决了(最后 - 非常痛苦) - 我必须构建自己的 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

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

关于rest - Powershell Invoke-RestMethod 缺少 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320581/

相关文章:

java - 如何通过自己的REST服务传递API异常输出?

java - SpringMVC、Gson 和 GAE 集成

swagger - ASP.NET 样板文件 : Constraining user Input DTO property value to specific set of values

node.js - 如何在 Swagger 中添加 API key

spring - Swagger UI 是否支持@PathVariable 绑定(bind)?

c# - 缺少基于任务的 WCF 服务的帮助说明

java - Spring 启动: Cannot access REST Controller on localhost (404)

powershell - 使用 Powershell 为 Word 文档添加页眉和页脚

c# - 如何允许 powershell 从 .net 核心 MVC web 应用程序下载 EXE?

.net - 如何通过 Powershell 创建位图