实施"记住"功能在ASP.NET MVC [英] Implementing "Remember Me" Feature in ASP.NET MVC

查看:226
本文介绍了实施"记住"功能在ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个记​​住我功能,我的登录表单。我使用ASP.NET MVC作为我的Web应用程序。我设法cookie的东西的工作,但我失败了自动登录的情况下,用户他/她之前检查记得我复选框。我知道问题是什么,但我不知道如何解决它。

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.

在我的HomeController我有以下几点:

In my HomeController I have the following:

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);
}

在我UserController中,我有登录的操作方法:

And in my UserController, I have the Login action method:

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);
    }
}

所以基本上,我想我会做的是重新从主控制器的情况下,有一个登录cookie在索引操作结果的用户。但问题是,RedirectToAction将触发GET登录操作方法,而不是在POST它负责记录在用户。

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.

我该怎么完全错误的这件事?或者是有一些方法,我可以使用RedirectToAction或其他任何方式调用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?

推荐答案

首先,你应该永远不会存储用户的cookie中的凭证。这是令人难以置信不安全。密码将与每一个请求传递以及存储在用户的计算机上的纯文本。

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.

二,不推倒重来,尤其是在安全性方面,你永远不会得到它的权利。

Second, don't reinvent the wheel, especially when security is concerned, you'll never get it right.

ASP.Net已经安全地提供此功能与形式Authenitcation和会员供应商。你应该看一看成说。创建默认MVC项目将包括基本身份验证设置。官方 MVC网站有更多的。

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 site has more.

更新

您仍然可以使用.NET窗体身份验证,但并不实现成员资格提供程序。在基本层面会像这样工作。

You can still use .NET forms authentication without implementing a membership provider. At a basic level it would work like this.

您启用窗体身份验证在你的web.config

You enable forms authentication in you 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]
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");

  }

}

这篇关于实施&QUOT;记住&QUOT;功能在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆