ASP.NET MVC记住我功能

3

我有一个ASP.NET MVC 4项目,用简单的身份验证。

我试图让我的网站在用户勾选“记住我”复选框时自动登录。 但是我遇到了问题。 关闭浏览器并重新打开后,用户从未登录过。

在查看(http://forums.asp.net/t/1654606.aspx#4310292)之后,我添加了一个由IIS生成的机器密钥。 我已经禁用了“运行时自动生成”和“为每个应用程序生成唯一密钥”,然后生成了密钥)。 不幸的是,这没有起作用。

查看使用ASP.NET MVC身份验证的“记住我”未能正常工作,我添加了一行FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe)但也没用,所以我现在将其注释掉了。

我尝试了ASP.NET MVC RememberMe上给出的答案,但似乎也不起作用。
我是否忽略了一些明显的东西?
//FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

if (model.RememberMe)
{
    //int timeout = model.RememberMe ? 525600 : 2; // Timeout in minutes,525600 = 365 days
    int timeout = 525600;
    var ticket = new FormsAuthenticationTicket(model.UserName, model.RememberMe, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);//My Line
    Response.Cookies.Add(cookie);
}

在浏览器中检查使用“记住我”功能和不使用该功能时的身份验证 cookie - 它是会话还是持久性的?这种行为是特定于特定浏览器还是所有浏览器通用的? - Lanorkin
看起来问题出在检查登录上,而不是实际登录,你有检查过你的 cookie 吗?如果你有一个 cookie(刷新后),那么你的问题就在读取/验证阶段。 - davethecoder
2个回答

3
这是我的操作方式。
public class MyAuthentication
{
    public static HttpCookie GetAuthenticationCookie(LoginModel model, bool persistLogin)
    {
         // userData storing data in ticktet and then cookie 
        JavaScriptSerializer js = new JavaScriptSerializer();

        var userData = js.Serialize(model);
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                 1,
                 "akash",
                 DateTime.Now,
                 DateTime.Now.AddHours(1),
                 persistLogin,
                 userData);

        string encTicket = FormsAuthentication.Encrypt(authTicket);
        HttpCookie cookie= new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        cookie.Expires = authTicket.Expiration; //must do it for cookie expiration 
        return cookie;
    }

    internal static bool Login(string UserName, string Password)
    {
        //UserName="akash" Password="akash"
        //check can be done by DB
        if (UserName== "akash" && Password == "akash")
            return true;
        else
            return false;
    }
}

然后

[HttpGet]
    [AllowAnonymous]
    public ActionResult Login()
    {
        //ViewBag.Message = "Your contact page.";
        HttpCookie cookie =  Request.Cookies[FormsAuthentication.FormsCookieName];
       // var ek = cookie.Value;
        try
        {
            //some times no cookie in browser
            JavaScriptSerializer js = new JavaScriptSerializer();
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            //string data = ticket.UserData;
            LoginModel model = js.Deserialize<LoginModel>(ticket.UserData);
            if (MyAuthentication.Login(model.UserName, model.Password) == true)
            {
                RedirectToAction("Index", "Home");
            }
        }
        catch
        {

        }
        return View();

您可以在Global.asax或授权筛选器上进行检查。 确保您的web.config中有

<authentication mode="Forms">
  <forms defaultUrl="/Home/Login" loginUrl="/home/Login" timeout="2880">
  </forms>
</authentication>

在所有控制器之前加上[Authorize]属性。


1
回答很好,但缺少一件事,我们还需要保存那个cookie。所以无论我们在哪里调用GetAuthenticationCookie,我们都需要执行以下操作:ControllerContext.HttpContext.Response.Cookies.Add(cookie); - Faran Shabbir

0
    builder.Services.AddControllersWithViews();
    var constr = builder.Configuration["ConnectionStrings:Default"];
    builder.Services.AddDbContext<AppDbContext>(opt =>
    {
        opt.UseSqlServer(constr);
    });
    builder.Services.AddIdentity<AppUser, IdentityRole>(opt =>
    {
        opt.Password.RequiredLength = 8;
        opt.Password.RequireDigit= true;
        opt.Password.RequireLowercase= true;
        opt.Password.RequireUppercase= true;
        opt.Password.RequireNonAlphanumeric= true;
        opt.User.RequireUniqueEmail= true;
        opt.Lockout.MaxFailedAccessAttempts= 5;
        opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(10);
        opt.Lockout.AllowedForNewUsers= true;
    }).AddEntityFrameworkStores<AppDbContext
().AddDefaultTokenProviders();
    
       builder.Services.AddSession(opt =>
       {
             opt.IdleTimeout = TimeSpan.FromSeconds(15);
       });
    
        builder.Services.ConfigureApplicationCookie(opt =>
    {
        opt.LoginPath = "/Auth/Login";
    });
app.UseSession();

app.UseAuthentication();
app.UseAuthorization();

请记住,Stack Overflow 不仅旨在解决当前的问题,还要帮助未来的读者找到类似问题的解决方案,这需要理解底层代码。对于我们社区中的初学者和不熟悉语法的成员来说,这尤其重要。鉴于此,您能否编辑您的答案,包括您正在做什么以及为什么您认为这是最好的方法的解释? - Jeremy Caney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接