asp.net-mvc 在 ASP.NET MVC 中实现“记住我”功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5619791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing "Remember Me" Feature in ASP.NET MVC
提问by Kassem
I'm trying to implement a "remember me" feature to my login form. I am using ASP.NET MVC as my web application. I managed to get the cookie stuff working, but I failed to automatically login the user in case he/she checked the remember me checkbox before. I know what the problem is but I do not know how to solve it.
我正在尝试在我的登录表单中实现“记住我”功能。我使用 ASP.NET MVC 作为我的 Web 应用程序。我设法让 cookie 的东西工作,但我未能自动登录用户,以防他/她之前选中了记住我复选框。我知道问题是什么,但我不知道如何解决它。
In my HomeController I have the following:
在我的 HomeController 中,我有以下内容:
private LoginViewModel CheckLoginCookie()
{
if (!string.IsNullOrEmpty(_appCookies.Email) && !string.IsNullOrEmpty(_appCookies.Password))
{
var login = new LoginViewModel
{
Email = _appCookies.Email,
Password = _appCookies.Password
};
return login;
}
return null;
}
public ActionResult Index()
{
var login = CheckLoginCookie();
if (login != null)
return RedirectToAction("Login", "User", login);
var viewModel = new HomeIndexViewModel
{
IntroText =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
LastMinuteDeals = new List<ItemsIndexViewModel>(),
TrustedDeals = new List<ItemsIndexViewModel>()
};
return View(viewModel);
}
And in my UserController, I have the Login action method:
在我的 UserController 中,我有 Login 操作方法:
public ActionResult Login()
{
return PartialView(new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel dto)
{
bool flag = false;
if (ModelState.IsValid)
{
if (_userService.AuthenticateUser(dto.Email, dto.Password, false)) {
var user = _userService.GetUserByEmail(dto.Email);
var uSession = new UserSession
{
ID = user.Id,
Nickname = user.Nickname
};
SessionManager.RegisterSession(SessionKeys.User, uSession);
flag = true;
if(dto.RememberMe)
{
_appCookies.Email = dto.Email;
_appCookies.Password = dto.Password;
}
}
}
if (flag)
return RedirectToAction("Index", "Home");
else
{
ViewData.Add("InvalidLogin", "The login info you provided were incorrect.");
return View(dto);
}
}
So basically, what I thought I would do is to redirect the user from the Index action result on the home controller in case there was a login cookie. But the problem is that the RedirectToAction will trigger the GET Login action method and not the POST which takes care of logging in the user.
所以基本上,我认为我会做的是从家庭控制器上的索引操作结果重定向用户,以防有登录cookie。但问题是 RedirectToAction 将触发 GET Login 操作方法,而不是负责登录用户的 POST。
Am I going completely wrong about this? Or is there some way I could call the POST Login method using RedirectToAction or any other way?
我完全错了吗?或者有什么方法可以使用 RedirectToAction 或任何其他方式调用 POST Login 方法?
回答by David Glenn
First off, you should never store the user's credentials in a cookie. It's incredibly insecure. The password will be passed with every request as well as being stored in plain text on the user's machine.
首先,您永远不应该将用户的凭据存储在 cookie 中。这是令人难以置信的不安全。密码将随每个请求一起传递,并以纯文本形式存储在用户机器上。
Second, don't reinvent the wheel, especially when security is concerned, you'll never get it right.
其次,不要重新发明轮子,尤其是当涉及到安全性时,你永远不会做对。
ASP.Net already provides this functionality securely with Forms Authenitcation and Membership Providers. You should take a look into that. Creating a default MVC project will include the basic authentication setup. The official MVC sitehas more.
ASP.Net 已经通过 Forms Authentication 和 Membership Providers 安全地提供了这个功能。你应该看看。创建默认 MVC 项目将包括基本身份验证设置。MVC官方网站有更多。
Update
更新
You can still use .NET forms authentication without implementing a membership provider. At a basic level it would work like this.
您仍然可以使用 .NET 表单身份验证,而无需实现成员资格提供程序。在基本层面上,它会像这样工作。
You enable forms authentication in you web.config
您在 web.config 中启用表单身份验证
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
You decorate the actions or the controllers you would like to secure with the [Authorize]
attribute.
您可以使用[Authorize]
属性来装饰您想要保护的操作或控制器。
[Authorize]
public ViewResult Index() {
//you action logic here
}
Then create a basic login action
然后创建一个基本的登录操作
[HttpPost]
public ActionResult Login(LoginViewModel dto) {
//you authorisation logic here
if (userAutherised) {
//create the authentication ticket
var authTicket = new FormsAuthenticationTicket(
1,
userId, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
rememberMe, //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);
return RedirectToAction("Index");
}
}