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:
HttpClient
, I do a get to a page containing the token. __RequestVerificationToken
with value from the hidden field.AntiForgery.Validate(xx,yy)
fails with error:
The provided anti-forgery token was meant for user X, but the current user is Y.I figured it out. It needs Forms Authentication to be done prior and pass the cookies in subsequent WebAPI calls. So here's the revised flow:
1) Load the login form using HttpWebRequest (GET)
2) Do a POST on the login form using credentials. Do supply a cookiecontainer in HttpWebRequest
3) The cookiecontainer now contains the Auth cookies and __RequestVerificationToken
4) Grab the __RequestVerificationToken from any subsequent GET or even from the output from login result
5) For the WebAPI Post call, pass the cookiecontainer as is. Also include a header __RequestVerificationToken with value from prev step.