【问题标题】:How can I correct Invalid CSRF token errors when calling a rest API?调用 REST API 时如何更正 Invalid CSRF token 错误?
【发布时间】:2015-05-02 06:18:13
【问题描述】:

我有一个脚本,它将查询 Web 休息服务以查找特定对象的 ID。我已经让查询在 Powershell 下对单个查询运行良好,但我需要运行数百个查询。为每个查询登录真的很慢(而且是不好的做法)。

我先让脚本登录到服务器并保存会话。我使用 post 操作运行其余查询。第一个工作正常。第二个炸弹说:

Invoke-RestMethod : Invalid CSRF Token 
Invalid CSRF Token
An invalid cross-site request forgery token was detected in the request.

代码如下所示:

$secpasswd = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("user", $secpasswd)

$headers = "Content-Type: text/plain","Accept: text/plain" 

#Login it the server to store the session to WebSession.
$login = Invoke-WebRequest -Uri "https://devrhapapp01:8444" -Credential $cred -SessionVariable websesssion

#This one returns correctly.
$Results = Invoke-RestMethod -Uri "https://devrhapapp01:8444/api/components/find" -ContentType "text/plain" -Method Post -Body "Search1" -WebSession $websesssion 
write-host $Results

#This one will give an error.
$Results = Invoke-RestMethod -Uri "https://devrhapapp01:8444/api/components/find" -ContentType "text/plain" -Method Post -Body "Search1" -WebSession $websesssion 
write-host $Results

【问题讨论】:

  • CSRF 令牌通常是每个请求的。您通常必须加载页面以获取令牌,然后使用我相信的请求提交该令牌。有获取新令牌的api吗?

标签: rest powershell csrf


【解决方案1】:

不确定发生了什么,但请尝试提交正确的防伪令牌:

$forgeryToken = ($login.InputFields | 
            Where { $_.name -eq "__RequestVerificationToken" }).value

$forgeryTokenPostData = "__RequestVerificationToken=$forgeryToken"

Invoke-WebRequest .... -Body $forgeryTokenPostData

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2021-03-19
    • 2016-05-07
    • 2021-10-19
    • 1970-01-01
    • 2020-03-25
    • 2017-05-21
    • 2022-01-22
    相关资源
    最近更新 更多