如何实现在MVC 4应用程序的登录界面中记住我 [英] how to implement remember me in Login screen of MVC 4 application
本文介绍了如何实现在MVC 4应用程序的登录界面中记住我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了以下代码,我不知道下次用户登录时检索用户名和密码的最佳方法是什么。
以下是用户提交用户ID和密码时调用的操作:
Hi,
I have written the following code, I do not know what is the best way to get the user name and password retrieved the next time the user logs in.
Below is the action i call when user submits the user id and password:
[ValidateAntiForgeryToken]
[HttpPost]
[AllowAnonymous]
public ActionResult Login(Login loginUser,string ReturnUrl = "")
{
ViewBag.loginErrorMsg = string.Empty;
#region Style 1
if (ModelState.IsValid)
{
if (loginUser.Username != null && IsAuthenticated(loginUser))
{
var authTicket = new FormsAuthenticationTicket(
1,
loginUser.Username, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
loginUser.RemeberMe, //true to remember
"", //roles
"/"
);
//encrypt the ticket and add it to a cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(loginUser.Username, false);
}
else
{
ViewBag.loginErrorMsg = Constants.LoginErrMsg;
}
}
#endregion
ModelState.Remove("Password");
return View();
}
虽然我尝试了各种方法来检索密码,但他们没有帮助。
截至目前,登录视图操作的代码很简单:
Although i tried various ways to retrieve the password they did not help.
The code at the Login view action is simple as of now:
[AllowAnonymous]
public ActionResult Login()
{
return View("Login");
}
我没有在操作Login()中获取密码。请让我知道如何检索保存的密码以防用户在登记时记住我之前的登录信息。
[ ^ ]
推荐答案
如果您要手动创建身份验证cookie,那么您需要确保将其设置为仅限HTTP。这样可以确保不会通过跨站点脚本漏洞窃取cookie。
如果您想要记住用户,那么只需增加身份验证票证的持续时间:
If you're going to manually create the authentication cookie, then you need to make sure it's set to "HTTP only". This ensures that the cookie cannot be stolen via a Cross-Site Scripting vulnerability.
If you want the user to be remembered, then simply increase the duration of the authentication ticket:
DateTime utcNow = DateTime.UtcNow;
DateTime utcExpires = loginUser.RemeberMe
? utcNow.AddDays(5)
: utcNow.AddMinutes(20);
var authTicket = new FormsAuthenticationTicket(
2,
loginUser.Username,
utcNow,
utcExpires,
loginUser.RemeberMe,
string.Empty,
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
cookie.HttpOnly = true;
if (loginUser.RemeberMe)
{
cookie.Expires = authTicket.Expiration;
}
Response.Cookies.Add(cookie);
试图记住用户的密码是一个非常糟糕的主意,并将导致您的应用程序中出现严重的安全漏洞。
如何构建(以及如何不构建)安全的记住我功能特洛伊亨特 [ ^ ]
这篇关于如何实现在MVC 4应用程序的登录界面中记住我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文