防伪处理令牌在winform和的WebAPI [英] Handle AntiForgery Token in Winform and WebAPI

查看:900
本文介绍了防伪处理令牌在winform和的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是对付防伪与 ValidateAntiForgeryTokenAttribute 方法属性,而从非浏览器客户端调用最好的办法,比方说的WinForm

根据我所知道的

,下面是伪造防工作原理是:


  1. 一个隐藏的输入字段添加到页面,例如


  2. 具有相同名字的cookie也发送到客户端


  3. 在接下来的要求,无论是饼干和隐藏的输入字段被发送到服务器。服务器调用 AntiForgery.Validate(令牌,饼干)来确认该请求是合法的。


所有的web应用程序工作正常。这似乎并不在WinForm的工作。这是我做的:


  1. 使用的HttpClient ,我做一个到达包含了记号的页面。

  2. 我解析页面并获取隐藏的输入字段。我也拿起饼干。

  3. 我通过cookie的原样。最重要的是,我添加了一个新的头 __ RequestVerificationToken 从隐藏字段的值。

  4. 我踏进服务器code。

  5. AntiForgery.Validate(XX,YY)失败,错误:
    提供的防伪标记是为了用户X,但目前用户为Y


解决方案

我想通了。它需要窗体身份验证将之前完成,通过饼干在随后的WebAPI调用。因此,这里的修改流程:

1)使用加载登录表单的HttpWebRequest(GET)

2)不要使用证书登录表单上POST。请提供一个的CookieContainer 在HttpWebRequest的

3)的CookieContainer现在包含验证饼干和 __ RequestVerificationToken

4)任何后续GET抓住__RequestVerificationToken甚至从登录的结果输出

5)为邮政的WebAPI调用,传递的CookieContainer原样。还包括标题 __RequestVerificationToken从$ P $光伏步进值。

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.

解决方案

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.

这篇关于防伪处理令牌在winform和的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆