What's the best way to deal with Antiforgery on methods with ValidateAntiForgeryTokenAttribute
attribute while calling from a non-browser client, say WinForm
?
Based on what I know, below is how anti forgery works:
A hidden input field is added to the page, e.g.
A cookie with the same name is also sent to the client
On the next request, both the cookie and the hidden input field is sent to server. Server calls
AntiForgery.Validate(token, cookie)
to confirm that the request is legit.
All works fine in a web app. It doesn't seem to work in WinForm. Here is what I do:
- Using
HttpClient
, I do a get to a page containing the token. - I parse the page and grab the hidden input field. I also pick up the cookie.
- I pass the cookie as is. On top of that, I add a new header
__RequestVerificationToken
with value from the hidden field. - I step into the server code.
- The
AntiForgery.Validate(xx,yy)
fails with error: The provided anti-forgery token was meant for user X, but the current user is Y.