mat*_*mat 1 asp.net-mvc antiforgerytoken asp.net-mvc-3
我正在尝试为我的MVC3应用程序实现AntiForgeryToken.设置FormAuthentication cookie后,我遇到了AntiForgeryToken的问题.这是一个简单的例子,它解释了我的问题.
我有家庭控制器与以下行动方法:
public class HomeController : Controller
{
public ActionResult Logon()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Logon(string userName, string password)
{
FormsAuthentication.SetAuthCookie(userName, false);
return View("About");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult About(FormCollection form)
{
return View("PageA");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的登录和关于视图:
Logon.cshtml:
@using (Html.BeginForm("Logon", "Home"))
{
@Html.AntiForgeryToken()
<label> UserName :</label>
<input name = "userName" type="text"/>
<br />
<label> Password :</label>
<input name = "password" type="password"/>
<br />
<br />
<input type="submit" value="LogOn" />
}
Run Code Online (Sandbox Code Playgroud)
About.cshtml
@using (Html.BeginForm("About", "Home"))
{
@Html.AntiForgeryToken()
<p> This is conent of page About</p>
<input name = "moreInfo" type="text"/>
<input type="submit" value="SubmitAbout" />
}
Run Code Online (Sandbox Code Playgroud)
我对"登录"帖子方法没有任何问题.它正在验证antiforgerytoken和渲染About视图.有趣的是,当我在"关于"视图上发帖时,我收到错误"未提供所需的防伪令牌或无效"
可能有人指出我在这里做错了什么?
感谢您的帮助.
我做了一些测试,并确定即使你打电话FormsAuthentication.SetAuthCookie(...),问题是httpContext.User.Identity.Name在请求期间仍然是空的.
因此,要解决此问题,您需要手动设置当前值User:
FormsAuthentication.SetAuthCookie(email, true);
this.HttpContext.User = new GenericPrincipal(new GenericIdentity(email), null);
Run Code Online (Sandbox Code Playgroud)
这将设置调用User时使用的正确Html.AntiForgeryToken()值.
请注意,普通PRG模式网站不需要此代码,因为重定向后,User将加载正确的.
此外,由于您的Logon方法需要有效的用户名和密码,因此它不太容易受到CSRF攻击,因此您可能不需要使用ValidateAntiForgeryToken该方法.也许这就是AntiForgeryToken依赖于用户名的原因.CSRF攻击通常只利用已经过身份验证的用户.