从webrequest中读取"Set-Cookie"标头,并在Powershell中发送cookie



我只使用powershell。

我有一个 url 可以先登录:https://.../login凭据

[string]$url = "http://blabla";
[string]$login = "$url/login";
[string]$user = "admin";
[string]$pass = "tester";
[string]$qs = "username=$user&password=$pass";
Invoke-WebRequest $login -Method Post -Body $qs -UseBasicParsing -SessionVariable session;

我从服务器那里得到了一些答案,例如:

Content-Length: 3 
Content-Type: text/plain; charset=UTF-8 
Set-Cookie:  SID=....; path=/

通过调用该请求,我想获取cookieSID,并在将来的调用中使用它:

Invoke-WebRequest $test -Method GET -UseBasicParsing -WebSession $session;

但是我得到了403错误。

如何为$test请求传递该cookie?

如果要手动从请求中提取Set-Cookie标头,则需要从响应中捕获它:

$response = Invoke-WebRequest $login ...
$response.Headers['Set-Cookie'] | ? { $_ -match '^SID' }

但我想指出的是,当您使用SessionVariable参数时,您已经捕获了您的 cookie:

$session.Cookies.GetCookies($url)

您可以通过执行以下操作将这些 Cookie 传递给新请求:

Invoke-WebRequest ... -WebSession $session

如果$test包含该输出并且是具有这些属性的对象,则可以使用以下属性。这将输出SID=....

($test.Set-Cookie -split ";")[0]

如果只需要SID的值,则可以使用:

($test.Set-Cookie -split ";" -split "SID=")[1]

最新更新