“Remember me” with ASP.NET MVC Authentication is not working
-
21-08-2019 - |
Question
I have a standard ASP.NET MVC (RC Refresh) web project, with the standard ASP.NET Membership provider and the Account controller that is included in the project template.
When I check "Remember me" in my Login form, I am still not being remembered by the site. (Firefox remembers my username and password, but what I expected to happen was to be automatically logged on).
Do I have to set and check the cookie manually? If so, how should it best be done?
Solution
You need to pass true/false to the SetAuthCookie method.
public ActionResult Login (string email, string password, bool rememberMe, string returnUrl)
{
// snip
FormsAuth.SetAuthCookie(username, rememberMe); // <- true/false
// snip
}
and make sure that bool rememberMe
reflects the status of the checkbox on your login page.
OTHER TIPS
You need to generate a persistent cookie in the controller method that handles logon when the Remember Me box is checked. If you are using RedirectFromLoginPage
, set the createPersistentCookie argument to true
.
These 3 methods helped me persist a cookie.
Note, if the user unselects "Remember Me", you'll want to remove the cookie.
private const string RememberMeCookieName = "MyCookieName";
private string CheckForCookieUserName()
{
string returnValue = string.Empty;
HttpCookie rememberMeUserNameCookie = Request.Cookies.Get(RememberMeCookieName);
if (null != rememberMeUserNameCookie)
{
/* Note, the browser only sends the name/value to the webserver, and not the expiration date */
returnValue = rememberMeUserNameCookie.Value;
}
return returnValue;
}
private void CreateRememberMeCookie(string userName)
{
HttpCookie rememberMeCookie = new HttpCookie(RememberMeCookieName, userName);
rememberMeCookie.Expires = DateTime.MaxValue;
Response.SetCookie(rememberMeCookie);
}
private void RemoveRememberMeCookie()
{
/* k1ll the cookie ! */
HttpCookie rememberMeUserNameCookie = Request.Cookies[RememberMeCookieName];
if (null != rememberMeUserNameCookie)
{
Response.Cookies.Remove(RememberMeCookieName);
rememberMeUserNameCookie.Expires = DateTime.Now.AddYears(-1);
rememberMeUserNameCookie.Value = null;
Response.SetCookie(rememberMeUserNameCookie);
}
}