How can I fix invalid CSRF token errors when calling rest API?
I have a script that will query the web service to find the id for a specific object. I got a request to work under Powershell for one request, but I need to run several hundred requests. It is very slow (and bad practice) to log in for every single request.
I have my first script logging into the server and saving the session. I am running a request for the remainder using the post operation. The first one works fine. The second bomb says:
Invoke-RestMethod : Invalid CSRF Token
Invalid CSRF Token
An invalid cross-site request forgery token was detected in the request.
The code looks like this:
$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
+3
source to share
1 answer
Not sure what's going on, but try to present the correct anti-forgery token:
$forgeryToken = ($login.InputFields |
Where { $_.name -eq "__RequestVerificationToken" }).value
$forgeryTokenPostData = "__RequestVerificationToken=$forgeryToken"
Invoke-WebRequest .... -Body $forgeryTokenPostData
0
source to share