且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实现在MVC 4应用程序的登录界面中记住我

更新时间:2023-02-19 19:00:46

如果您要手动创建身份验证cookie,那么您需要确保将其设置为仅限HTTP。这样可以确保不会通过跨站点脚本漏洞窃取cookie。



如果您想要记住用户,那么只需增加身份验证票证的持续时间:

If you're going to manually create the authentication cookie, then you need to make sure it's set to "HTTP only". This ensures that the cookie cannot be stolen via a Cross-Site Scripting vulnerability.

If you want the user to be remembered, then simply increase the duration of the authentication ticket:
DateTime utcNow = DateTime.UtcNow;

DateTime utcExpires = loginUser.RemeberMe 
    ? utcNow.AddDays(5) 
    : utcNow.AddMinutes(20);

var authTicket = new FormsAuthenticationTicket(
    2,
    loginUser.Username,
    utcNow,
    utcExpires,
    loginUser.RemeberMe,
    string.Empty,
    "/"
);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
cookie.HttpOnly = true;

if (loginUser.RemeberMe)
{
    cookie.Expires = authTicket.Expiration;
}

Response.Cookies.Add(cookie);



试图记住用户的密码是一个非常糟糕的主意,并将导致您的应用程序中出现严重的安全漏洞。



如何构建(以及如何不构建)安全的记住我功能特洛伊亨特 [ ^ ]