“Remember me” in ASP.net MVC 2.0

I had to create the “remember me” functionality in the login page for one of our customers. Never had to think about this before and it seems so simple at first. Which it actually is. First of all add a checkbox within the Views\Account\logon.aspx page:

<div class="editor-label rememberme">
<%= Html.CheckBox("rememberme" , ViewData["rememberme"]) %>
<label for="rememberme"> Remember me</label></div>

Add following in the Controllers\AccountController.cs file:

public ActionResult LogOn()
{

   string userName = "";
   bool rememberme = false;

   if (Request.Browser.Cookies)
   {
      HttpCookie cookieRememberme = Request.Cookies["rememberme"];
      if (cookieRememberme != null) {
         rememberme = (cookieRememberme.Value.ToLower() == "true");
      }
      ViewData["rememberme"] = rememberme;
      HttpCookie cookieUserName = Request.Cookies["username"];
      if (cookieUserName != null)
      {
         userName = cookieUserName.Value;
      }
   }

   if (User.Identity.IsAuthenticated)
   {
      FormsAuth.SignIn(userName, rememberme);

      return doLogon(userName);
   }
   return View();
}

[HttpPost]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Needs to take same parameter type as Controller.Redirect()")]
public ActionResult LogOn(string userName, string password, string returnUrl, bool rememberme)
{
   if (!ValidateLogOn(userName, password))
   {
      return View();
   }
   FormsAuth.SignIn(userName, rememberme);
   if (Request.Browser.Cookies)
   {
      HttpCookie cookie = new HttpCookie("rememberme");
      cookie.Value = rememberme.ToString();
      cookie.Expires = DateTime.Now.AddMonths(1);
      System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

      cookie = new HttpCookie("username");
      cookie.Value = userName;
      cookie.Expires = DateTime.Now.AddMonths(1);
      System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
   }
   return doLogon(userName);
}

private ActionResult doLogon(string userName)
{
   if (Roles.IsUserInRole(userName, "Administrator"))
   {
      return RedirectToAction("Home", "Admin");
   }
   else if (Roles.IsUserInRole(userName, "User"))
   {
      return RedirectToAction("blabla", "User");
   }
   return RedirectToAction("LogOn", "Account");
}

Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

*
*
*

Back To Top