1

Я попытался использовать Al настройки на web.config и UseCookieAuthentication() методы, как указано на многих темах в Интернете, как указано ниже:Тайм-аут сеанса не работает в ASP.NET MVC

Session timeout does not work (is set in web.config)

How to set session timeout in web.config

mvc 5 session timeout after default period (20 mins)

Однако, пытаясь изменить тайм-аут сеанса до 1 минуты (для тестирования) всех опций в этой конфигурации или методах не имеют никакого смысла, и я не конечно, где ошибка. Ниже приведены конфигурации, которые я изменил. Любая идея исправить проблему? Мне также необходимо уточнить, что лучше всего установить тайм-аут сеанса в приложении MVC: в web.config или в классах Auth?

web.config:

<system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" executionTimeout="60" /> 

    <sessionState mode="InProc" timeout="1" />  

    <!-- For LDAP --> 
    <httpCookies httpOnlyCookies="true" /> 
    <authentication mode="Forms"> 

     <!-- Note: I also remove this part and try with only "sessionState" --> 
     <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="1" 
      slidingExpiration="false" protection="All" /> 
    </authentication> 
</system.web> 


Startup.Auth.cs:

public void ConfigureAuth(IAppBuilder app) 
{ 
    // Code removed for brevity. 

    // Configure the sign in cookie 
    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.FromMinutes(1), 
       regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
     } 
    });    
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

    app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(1)); 
    app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);   
} 

ответ

2

Если вы используете ASP.NET Identity вам не нужно использовать настройки в web.config. Просто добавьте эти две строки в метод UseCookieAuthentication(), как показано ниже:

...., 
SlidingExpiration = true, 
ExpireTimeSpan = TimeSpan.FromMinutes(1) 
... 

Итак, окончательный код вашего метода будет выглядеть, как показано ниже:


Startup.Auth.cs :

public void ConfigureAuth(IAppBuilder app) 
{ 
    // Code removed for brevity. 

    // Configure the sign in cookie 
    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.FromMinutes(30), 
       regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
     },    
     SlidingExpiration = true, 
     ExpireTimeSpan = TimeSpan.FromMinutes(1) //Set the session timeout at here 
    });    
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

    app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(1)); 
    app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);   
} 


Для получения дополнительной информации, пожалуйста, посетите ASP.NET-Identity-Cookie-Authentication-Timeouts. Надеюсь, это поможет ...

 Смежные вопросы

  • Нет связанных вопросов^_^