tco*_*ode 18 asp.net-mvc antiforgerytoken razor asp.net-mvc-4
我最近把Live使用MVC 4和Entity Framework 5构建的Web应用程序.该MVC应用程序使用剃刀意见.
我注意到使用Elmah,当用户登录应用程序时,有时他们会收到以下错误
The provided anti-forgery token was meant for user "" but the current user is "user"
Run Code Online (Sandbox Code Playgroud)
我已经就如何解决这个问题做了一些研究,但似乎没有什么对我有用.请参阅下面的我的登录视图和相应的控制器操作.
剃刀视图
@if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="formEl_a">
<fieldset>
<legend>Login Information</legend>
<div class="lbl_a">
Email
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Email, new { @class = "inpt_a" })<br />
@Html.ValidationMessageFor(m => m.Email)
</div>
<div class="lbl_a">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field sepH_b">
@Html.PasswordFor(m => m.Password, new { @class = "inpt_a" })<br />
@Html.ValidationMessageFor(m => m.Password)
</div>
</fieldset>
</div>
<br />
<p>
<input type="submit" value="Log In" class="btn btn_d sepV_a" />
</p>
}
}
Run Code Online (Sandbox Code Playgroud)
调节器
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && _accountService.Logon(model.Email, model.Password, true))
{
//Validate
}
else
{
// inform of failed login
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得这一切看起来还不错,但错误仍然存在.有没有关于如何解决这个问题的想法?
非常感谢您的帮助.
谢谢.
Moh*_*our 11
针对AntiForgeryToken运行的验证代码还会检查您登录的用户凭据是否未更改 - 这些也在cookie中加密.这意味着,如果您在弹出窗口或其他浏览器选项卡中登录或注销,则表单提交将失败,并出现以下异常:
System.Web.Mvc.HttpAntiForgeryException (0x80004005):
The provided anti-forgery token was meant for user "", but the current user is "SomeOne".
Run Code Online (Sandbox Code Playgroud)
您可以通过将关闭这个功能AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;在Application_Start方法内部Global.asax文件.
当AntiForgeryToken未验证您的网站时将抛出异常类型System.Web.Mvc.HttpAntiForgeryException.通过捕获HttpAntiForgeryException,至少为用户提供针对这些异常的信息更丰富的页面,可以使这更容易一些.
private void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpAntiForgeryException)
{
Response.Clear();
Server.ClearError(); //make sure you log the exception first
Response.Redirect("/error/antiforgery", true);
}
}
Run Code Online (Sandbox Code Playgroud)
更多信息:
Html.AntiForgeryToken - 平衡安全性和可用性