微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – 在ASP.NET MVC中实现“记住我”功能

我试图在我的登录表单上实现“记住我”功能。我正在使用ASP.NET MVC作为我的Web应用程序。我设法使cookie的工作正常,但是我没有自动登录用户,以防他/她检查之前记住我的复选框。我知道问题是什么,但我不知道如何解决它。

在我的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);
}

在我的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);
    }
}

所以基本上,我想我会做的是将用户从Index操作结果重定向到主控制器,以防有一个登录cookie。但是问题是,RedirectToAction将触发GET登录操作方法,而不是POST用于注册用户

我完全错了吗?还是有一些方法可以使用RedirectToAction或任何其他方式调用POST登录方法

解决方法

首先,您不应该将用户的凭据存储在cookie中。这是非常不安全的。密码将按照每个请求进行传递,并以用户的机器上的纯文本格式存储。

第二,不要重新发明,特别是在安全方面,你永远都不会这样做。

ASP.Net已经通过Forms Autonitcation和Membership Providers安全地提供了这个功能。你应该看看。创建认的MVC项目将包括基本身份验证设置。官方MVC site有更多。

更新

您仍然可以使用.NET表单身份验证而不实现成员资格提供程序。在一个基本的水平上,它将像这样工作。

您在web.config中启用表单身份验证

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

您使用[授权]属性来装饰您想要保护的动作或控制器。

[Authorize]
public ViewResult Index() {
  //you action logic here
}

然后创建一个基本的登录操作

[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");

  }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you