“Remember me” with ASP.NET MVC Authentication is not working

假装没事ソ 提交于 2019-12-01 03:11:55
Todd Smith

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.

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);
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!