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

醉酒当歌 提交于 2019-12-19 05:13:12

问题


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?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/513949/remember-me-with-asp-net-mvc-authentication-is-not-working

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