ASP.NET-Identity-Cookie-Authentication-Timeouts (edit)

https://www.jamessturtevant.com/posts/ASPNET-Identity-Cookie-Authentication-Timeouts/

If you are using cookie authentication in ASP.NET Identity 2.1, there are two timeout settings that look similar upon first glance, ValidateInterval and ExpireTimespan:

 app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(15),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
    },
    SlidingExpiration = false,
    ExpireTimeSpan = TimeSpan.FromMinutes(30)
});

ExpireTimeSpan

CookieAuthenticationOptions.ExpireTimespan is the option that allows you to set how long the issued cookie is valid for. In the example above, the cookie is valid for 30 minutes from the time of creation. Once those 30 minutes are up the user will have to sign back in becuase the SlidingExpiration is set to false.

If SlidingExpiration is set to true then the cookie would be re-issued on any request half way through the ExpireTimeSpan. For example, if the user logged in and then made a second request 16 minutes later the cookie would be re-issued for another 30 minutes. If the user logged in and then made a second request 31 minutes later then the user would be prompted to log in.

SecurityStampValidator Validation Interval

The validateInterval of the SecurityStampValidator.OnValidateIdentity function checks the security stamp field to insure validity of the cookie after the given internval. This is not the same as checking expiration of the cookie, although it can cause the same result of being logged out.

The Security Stamp is created anytime a password is created/changed or an external login is added/removed. If a user changes their password then the SecurityStamp will be updated. This results in any cookie that might have been issued previous to the password change to become invalid the next time the validateInterval occurs.

For a concrete example using the above settings (this is a unlikely example but gets the point across):

  1. User signs in at location A.
  2. Same User changes work stations and signs in 10 minutes later at location B.
  3. Same User changes their password at location B at the 12 minute mark.
  4. The Same user goes back the the work station at location A and issues a request at the 20 minute mark.
  5. Since the User issued a request after the validateInterval at location A they will be signed-out and prompted for their credentials again.

When the user is signed out in this scenario it is different from the the cookie timing out because the 30 minute Expire Time Out was never reached. Yet the user is logged out because the validateInterval of the SecurityStampValidator.OnValidateIdentity was set to 15 minutes.

The differences

The difference is subtle at first glance but provides some great benefits, such as Sign-out Everywhere. But it can be confusing since the default ASP.NET Identity template only has validateInterval leaving the ExpireTimespan hidden and set to the default of 14 days. Without some digging a developer new to the ASP.NET Identity library might not immediately recognize that the validateInterval is not the same as expiring cookies on a given time fame.

Display Session Expire Popup

http://www.intstrings.com/ramivemula/articles/display-session-expire-popup-in-asp-net-mvc/ (CODE)

https://www.codeproject.com/Articles/616634/ASP-NET-MVC-How-To-Show-A-Popup-Warning-Before-Ses (CODE)

https://stackoverflow.com/questions/50187802/how-to-display-asp-net-identity-cookie-expire-popup-in-mvc

Forms Authentication

ASP.NET MVC - How To Show A Popup Warning Before Session Timeout - ASP.NET MVC

http://codemodus.blogspot.com/2016/06/aspnet-mvc-how-to-show-popup-warning.html

https://stackoverflow.com/questions/50187802/how-to-display-asp-net-identity-cookie-expire-popup-in-mvc

Session Expires in ASP.NET WebForms

https://www.aspsnippets.com/Articles/Display-Session-Timeout-message-before-Session-expires-in-ASPNet.aspx

Session Expires

https://stackoverflow.com/questions/33552566/session-timeout-warning-dialogs-mvc

https://www.codeproject.com/Articles/227382/Alert-Session-Time-out-in-ASP-Net

https://stackoverflow.com/questions/25423464/redirect-to-specific-page-after-session-expires-mvc4 (Use the [SessionAuthorize])

https://stackoverflow.com/questions/23090706/how-to-know-when-owin-cookie-will-expire

Good Articles

https://stackoverflow.com/questions/19456008/how-do-i-access-microsoft-owin-security-xyz-onauthenticated-context-addclaims-va

https://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux (CODE)

https://www.techcartnow.com/increase-timeout-asp-net-application/

http://www.khalidabuhakmeh.com/best-way-to-secure-a-user-s-password-in-c (MAKE PASSWORD STRONG)

Microsoft Docs - Session Timeout Warning in ASP.NET

SessionTimeoutWarning

https://blog.fairwaytech.com/2012/01/handling-session-timeout-gracefully

http://techtalklive.org/ttlblog/creating-session-expired-countdown/

https://blogs.perficient.com/2014/02/11/gracefully-handle-mvc-user-session-expiration-in-javascript/

https://blogs.perficient.com/2014/02/11/gracefully-handle-mvc-user-session-expiration-in-javascript/

A Javascript based single page app with a .NET backend that authenticates Azure AD users and calls the backend web api using access tokens, without using any SPA frameworks.

https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi

An ASP.NET MVC Web API protected by Azure AD that receives tokens from a client and uses ADAL to get tokens for calling the MIcrosoft Graph (for .NET 4.5)

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

https://www.aspforums.net/Threads/118683/Display-Session-Timeout-message-when-user-idle-in-Browser-using-JavaScript/

https://blogs.perficient.com/2014/02/11/gracefully-handle-mvc-user-session-expiration-in-javascript/

CodeProject.com

https://www.codeproject.com/Tips/1175658/Session-Expiration-Popup (HAY HAY HAY)

https://www.aspdotnet-suresh.com/2012/06/jquery-show-session-timeout-message.html

https://rigoneri.github.io/timeout-dialog.js/ (HAY HAY HAY)

https://www.macaw.nl/inspiratie/blogs/implementing-european-cookie-law-compliance-in-asp-net-mvc

https://www.macaw.nl/inspiratie/blogs/implementing-european-cookie-law-compliance-in-asp-net-mvc (HAY HAY HAY)

https://www.macaw.nl/inspiratie/blogs/implementing-european-cookie-law-compliance-in-asp-net-mvc

https://www.jqueryscript.net/other/Session-Timeout-Alert-Plugin-With-jQuery-userTimeout.html

https://www.itworld.com/article/2832447/how-to-create-a-session-timeout-warning-for-your-web-application-using-jquery.html

https://www.codeproject.com/Articles/711196/Session-Time-Out-Warning-Message-Using-jQuery-in-A

http://www.dotnetspider.com/forum/326114-How-show-popup-warning-before-session-timeout-aspnet-mvc-3.aspx

https://community.devexpress.com/blogs/aspnet/archive/2011/07/11/asp-net-mvc-how-to-show-a-popup-warning-before-session-timeout-aspnetmvc.aspx

ASP.NET Web API

http://benedict-chan.github.io/blog/2014/02/11/asp-dot-net-mvc-how-to-handle-unauthorized-response-in-json-for-your-api/

https://leastprivilege.com/2012/06/19/session-token-support-for-asp-net-web-api/

ASP.NET Identity and OWIN

https://markfreedman.com/handling-session-and-authentication-timeouts-in-asp-net-mvc/

https://stackoverflow.com/questions/20737578/asp-net-sessionid-owin-cookies-do-not-send-to-browser

https://world.episerver.com/forum/developer-forum/-Episerver-75-CMS/Thread-Container/2018/4/timeout-ignored-by-aspnet-identity-and-owin/

https://world.episerver.com/forum/developer-forum/-Episerver-75-CMS/Thread-Container/2018/4/timeout-ignored-by-aspnet-identity-and-owin/

https://www.hanselman.com/blog/WeirdTimeoutsWithCustomASPNETFormsAuthentication.aspx

ASP.NET-Identity-Cookie-Authentication-Timeouts

https://stackoverflow.com/questions/37086645/how-to-set-asp-net-identity-cookies-expires-time/37090696

If IsPersistent property of AuthenticationProperties is set to false, then the cookie expiration time is set to Session.

If checkbox "remember me" is checked then AuthenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = true }, userIdentity); will create a cookie with expiration time equal to ExpireTimeSpan you set up in Startup.cs (defaults to 14 days).

If checkbox "remember me" is NOT checked then you have to useAuthenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)}, userIdentity);. Again IsPersistent is set to true but now we give a value to ExpiresUtc so it does not use from CookieAuthenticationOptions from Startup.cs.

public override async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
{
    var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();
    // Clear any partial cookies from external or two factor partial sign ins
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
    if (rememberBrowser)
    {
        var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity);
    }
    else
    {
        //AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity);
        if (isPersistent)
        {
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, userIdentity);
        }
        else
        {
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }, userIdentity);
        }        
    }
}