0

Всем привет. Столкнулся с такой вот проблемой: Необходимо продлить сессию пользователя до максимально возможной. Вот код самого класса при помощи, которого авторизую пользователя:

public static class AuthenticationExtensions
{
    public const string StringValueType = "http://www.w3.org/2001/XMLSchema#string";

    public static void SignIn(this Controller controllerBase, CustomerUserSM  user, bool isPersistent = false)
    {
        var authenticationManager = controllerBase.HttpContext.GetOwinContext().Authentication;
        authenticationManager.SignIn();
        authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.FullName, StringValueType));
        identity.AddClaim(new Claim(ClaimTypes.Email, user.Email, StringValueType));
        identity.AddClaim(new Claim(ClaimTypes.Role, user.Role, StringValueType));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.PKID.ToString()));

        authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
    }

    public static void SignOut(this Controller controllerBase)
    {
        var authenticationManager = controllerBase.HttpContext.GetOwinContext().Authentication;
        authenticationManager.SignOut();
    }
}

Пробовал в Web.config указывать:

<authentication mode="Forms">
  <forms timeout="99999999"/>
</authentication>
<sessionState timeout="525500" />

Однако это не помогло.

1
  • Сессия (sessionState) и аутентификация (forms / identity) - это совершенно разные вещи. sessionState - это браузерная сессия, а не сессия пользователя.
    – user177221
    6 янв 2017 в 15:04

2 ответа 2

0

Пропишите ExpireTimeSpan в CookieAuthenticationOptions:

public void ConfigureAuth(IAppBuilder app)
{            
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        ExpireTimeSpan = TimeSpan.FromMinutes(30) // значение побольше
    });
}
0

Спасибо, но решил уже проблему путем изменения времени в следующем коде:

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromHours(500),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });   
2
  • там вроде бы два таймаута - validateInterval -как часто проверять на случай смены пароля, и ExpireTimeSpan - время жизни самой куки.
    – user177221
    6 янв 2017 в 15:43
  • ну вроде как уже пару дней не логаутило, а про ExpireTimeSpan почитаю, спасибо большое!
    – Just3f
    8 янв 2017 в 16:47

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.