Handle AntiForgery Token in Winform and WebAPI

2019-07-03 09:24发布

问题:

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:

  1. A hidden input field is added to the page, e.g.

  2. A cookie with the same name is also sent to the client

  3. 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:

  1. Using HttpClient, I do a get to a page containing the token.
  2. I parse the page and grab the hidden input field. I also pick up the cookie.
  3. I pass the cookie as is. On top of that, I add a new header __RequestVerificationToken with value from the hidden field.
  4. I step into the server code.
  5. The AntiForgery.Validate(xx,yy) fails with error: The provided anti-forgery token was meant for user X, but the current user is Y.

回答1:

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.