Постоянные Файлы Cookie Удаляются При Закрытии Браузера-Identity 2.0



Я использую asp.net identity 2.0 для управления логинами пользователей.
Я следую примеру для Identity 2.0 и не могу заставить файл cookie сохраняться после закрытия всего браузера. Это происходит во всех браузерах.



Код:



Контролер Счета



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


Запуск.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()))
}
});


Извините за стену кода, но я не вижу, что я делаю неправильно, что печенье не будет сохраняться для 3 часы, когда браузер был закрыт без ручного выхода из системы?

632   1  

1 ответ:

Проблема заключается в ошибке в OnValidateIdentity, которая при регенерации файла cookie в настоящее время всегда устанавливает IsPersistent в false (даже если исходный файл cookie был постоянным). Таким образом, поскольку вы установили validateInterval равным 0 (всегда проверяйте каждый запрос), вы фактически никогда не получите постоянный файл cookie.

Comments

    Ничего не найдено.