Handle AntiForgery Token in Winform and WebAPI

让人想犯罪 __ 提交于 2019-12-23 16:09:30

问题


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.



来源:https://stackoverflow.com/questions/14467804/handle-antiforgery-token-in-winform-and-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!