Use AntiForgery token in Winform and WebAPI
What is the best way to deal with Antiforgery in attributed methods ValidateAntiForgeryTokenAttribute
when called from a client without a browser, say WinForm
?
Based on what I know, below is how anti-spoofing works:
-
A hidden input field is added to the page, for example.
-
A cookie with the same name is also sent to the client
-
On the next request, both the cookie and the hidden input field are sent to the server. The server calls
AntiForgery.Validate(token, cookie)
to confirm that the request is legitimate.
Everything works fine in the web app. It doesn't seem to work in WinForm. That's what I'm doing:
- By using
HttpClient
, I access the page containing the token. - I am parsing the page and grabbing a hidden input field. I also take cookie.
- I am passing the cookie as is. Also, I am adding a new title
__RequestVerificationToken
with a value from a hidden field. - I go into the server code.
- Failed Error
AntiForgery.Validate(xx,yy)
: The provided anti-forgery token is for user X, but the current user is Y.
source to share
I understood that. Forms authentication requires pre-validation and passing cookies in subsequent WebAPI calls. So here's the revised thread:
1) Load the login form with HttpWebRequest (GET)
2) Make a POST on the login form using your credentials. Provide cookieontainer on HttpWebRequest
3) Cookieontainer now contains Auth and __ RequestVerificationToken cookies
4) Take __RequestVerificationToken from any subsequent GET or even from the login result
5) For WebAPI post call pass cookiecontainer as is. Also include a header __RequestVerificationToken with the value from the previous step.
source to share