3

I've got a project based in ASP.NET MVC 4 that simple authentication.

I'm trying to get my site to automatically log the user in when they check the remember me checkbox. However I'm having problems getting this working. After closing down the browser and reopening it the user is never logged in.

After checking (http://forums.asp.net/t/1654606.aspx#4310292) I've added a machine key in, generated by IIS. I've set automatically generate at runtime and generate a unique key for each application have both been disabled and I've Generated Keys). Unfortunately this hasn't worked.

Looking at "Remember me" with ASP.NET MVC Authentication is not working, I've added in the line FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe) but that didn't work either so I've now commented it out.

I tried the answer given on ASP.NET MVC RememberMe but that doesn't seem to work either.

Am I missing something obvious?

//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);
}
Community
  • 1
  • 1
Jay
  • 878
  • 3
  • 12
  • 22
  • Check resulted authentication cookie in browser with and without "remember me" feature - is it session or persistent? Is this behavior specific for specific browser, or for all browsers? – Lanorkin Jul 23 '14 at 07:50
  • looks to me to be a problem with the check login, rather than actually login, have you checked yours cookies to see if you have one ???? if you have a cookie ( after refresh ) then your problem is at the reading stage / Validation – davethecoder Jul 23 '14 at 12:36

2 Answers2

3

this is how i do it

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

and then

[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();

you can check it on Global.asax or authorization filter. make sure you have web.config has

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

and [Authorize] attribute before all controller.

Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45
  • 1
    Excellent answer but one thing is missing, we need to save that cookie as well. So wherever we call GetAuthenticationCookie we need to do this next: ControllerContext.HttpContext.Response.Cookies.Add(cookie); – Faran Shabbir Feb 15 '18 at 20:06
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();
DevR2
  • 1
  • 1
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Jan 27 '23 at 20:28