问题描述
我在 ASP.NET MVC 4 中使用默认登录模块.我没有更改默认应用程序中的任何代码,而是将其托管在共享服务器上.
在我使用默认登录页面登录后.我让浏览器闲置了一段时间.当我尝试使用 [Authorize]
属性执行任何控制器操作时,显然应用程序重定向到登录页面.
然后我再次尝试登录,但当我点击登录按钮时出现错误.
防伪 cookie 令牌和表单字段令牌不匹配.
登录操作
//POST:/Account/Login[HttpPost][允许匿名][验证AntiForgeryToken]公共 ActionResult 登录(LoginModel 模型,字符串 returnUrl){if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)){返回重定向到本地(returnUrl);}//如果我们到了这一步,有些事情失败了,重新显示表单ModelState.AddModelError("", "提供的用户名或密码不正确.");返回视图(模型);}
我通过在 web.config 中显式添加机器密钥解决了这个问题.
注意:出于安全原因,请勿使用此密钥.从 https://support.microsoft.com/en-us/kb/生成一个2915218#附录A.不要使用在线-一,详情,http://blogs.msdn.com/b/webdev/archive/2014/05/07/asp-net-4-5-2-and-enableviewstatemac.aspx >
<的machineKey的validationKey = 971E32D270A381E2B5954ECB4762CE401D0DF1608CAC303D527FA3DB5D70FA77667B8CF3153CE1F17C3FAF7839733A77E44000B3D8229E6E58D0C954AC2E796B" decryptionKey = 1D5375942DA2B2C949798F272D3026421DDBD231757CA12C794E68E9F8CECA71" 验证= SHA1" 解密= AES"/>
这是一个生成唯一机器密钥的站点:
http://www.developerfusion.com/tools/generatemachinekey/
I'm using the default login module in ASP.NET MVC 4. I did not change any code in the default application and i hosted it on a shared server.
After i logged in using default login page. i kept the browser idle for some time. Then obviously application redirected to the login page when i try to perform any controller action with [Authorize]
attribute.
Then i try to login again and it gives an error when i click on login button.
The anti-forgery cookie token and form field token do not match.
LogIn action
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
I resolved the issue by explicitly adding a machine key in web.config.
Note: For security reason don't use this key. Generate one from https://support.microsoft.com/en-us/kb/2915218#AppendixA. Dont use online-one, details, http://blogs.msdn.com/b/webdev/archive/2014/05/07/asp-net-4-5-2-and-enableviewstatemac.aspx
<machineKey validationKey="971E32D270A381E2B5954ECB4762CE401D0DF1608CAC303D527FA3DB5D70FA77667B8CF3153CE1F17C3FAF7839733A77E44000B3D8229E6E58D0C954AC2E796B" decryptionKey="1D5375942DA2B2C949798F272D3026421DDBD231757CA12C794E68E9F8CECA71" validation="SHA1" decryption="AES" />
Here's a site that generates unique Machine Keys:
http://www.developerfusion.com/tools/generatemachinekey/
这篇关于MVC 4 中的防伪 cookie 令牌和表单字段令牌不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!