有时我的部署服务器中存在此问题,这使我发疯,因为我无法在localhost中进行复制,我曾尝试在web.config中添加机器密钥,但到目前为止还算运气。
它只发生在登录页面。
我的版面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<form id="__AjaxAntiForgeryForm" action="#" method="post">
@Html.AntiForgeryToken()
</form>
<div class="wcenter">
@Html.Partial("_LoginPartial")
</div>
<br />
<div class="wcenter">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/pluginjs")
@Scripts.Render("~/bundles/customjs")
@RenderSection("scripts", required: false)
</body>
</html>
我的登录页面
@model LoginViewModel
@{
ViewBag.Title = "Log in";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username)
@Html.ValidationMessageFor(m => m.Username)
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
<input type="submit" value="LOGIN" />
}
控制器:
[AllowAnonymous]
public ActionResult Login()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
{
return View(model);
}
var user = new ApplicationUser() { UserName = model.Username, Id = model.Username };
var result = await UserManager.CheckPasswordAsync(user, model.Password);
if (result == true)
{
if (UserManager.FindByName(user.UserName) == null)
{
var res = UserManager.Create(user);
if (!res.Succeeded)
{
ModelState.AddModelError("", res.Errors.FirstOrDefault());
return View(model);
}
}
SignInManager.SignIn(user, true, true);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
任何帮助将不胜感激。
最佳答案
这是因为您要创建2个防伪令牌,一个在表单内,另一个在局部视图中。因此,有时CSRF创建的cookie与CSRF输入隐藏字段不匹配
关于c# - 防伪 token 无法解密&防伪cookie token 和表单字段 token 在部署中不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34348830/