Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent Cookie Being Deleted On Browser Close - Identity 2.0

I am using asp.net identity 2.0 to manage user logins. I am following the sample for Identity 2.0 and cannot get the cookie to persist after the whole browser is closed. This is happening on all browsers.

Code:

Account Controller

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    var result = await SignInHelper.PasswordSignIn(model.Email, model.Password, isPersistent: true, shouldLockout: true);

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);

        case SignInStatus.LockedOut:
            return View("Lockout");

        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

SignInHelper

public async Task<SignInStatus> PasswordSignIn(string userName, string password, bool isPersistent, bool shouldLockout)
{
    var user = await UserManager.FindByNameAsync(userName);
    if (user == null)
    {
        return SignInStatus.Failure;
    }

    if (await UserManager.IsLockedOutAsync(user.ID))
    {
        return SignInStatus.LockedOut;
    }

    if (await UserManager.CheckPasswordAsync(user, password))
    {
        // password verified, proceed to login
        return await SignIn(user, isPersistent);
    }

    if (shouldLockout)
    {
        await UserManager.AccessFailedAsync(user.ID);
        if (await UserManager.IsLockedOutAsync(user.ID))
        {
            return SignInStatus.LockedOut;
        }
    }

    return SignInStatus.Failure;
}

-

private async Task<SignInStatus> SignIn(User user, bool isPersistent)
{
    await SignInAsync(user, isPersistent);
    return SignInStatus.Success;
}

-

public async Task SignInAsync(User user, bool isPersistent)
{
    var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
    AuthenticationManager.SignIn(
       new AuthenticationProperties
        {
           IsPersistent = isPersistent
        },
        userIdentity
    );
}

Startup.Auth

app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
       AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
       CookieName = "ApplicationCookie",
       LoginPath = new PathString("/Account/Login"),
       ExpireTimeSpan = System.TimeSpan.FromMinutes(180), // 3 hours
       SlidingExpiration = true,
       Provider = new CookieAuthenticationProvider
       {
          OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
               validateInterval: TimeSpan.FromMinutes(0),
               regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
               getUserIdCallback: (user) => (user.GetGuidUserId()))
       }
   });

Sorry for the wall of code, but I can't see what I am doing wrong, that the cookie wouldn't be persisted for the 3 hours, when the browser was closed without manually logging off?

like image 374
Jenkie Avatar asked Jul 02 '14 11:07

Jenkie


1 Answers

The issue is with a bug in the OnValidateIdentity which when regenerating the cookie currently always sets IsPersistent to false (even if the original cookie was persistent). So because you set validateInterval to 0 (always validate every request), you effectively never will get a persistent cookie.

like image 92
Hao Kung Avatar answered Oct 12 '22 08:10

Hao Kung