Eric Brown - Cal
Eric Brown - Cal

Reputation: 14399

Asp.Net Identity2, How to detect when the cookie expires

I'm using Identty 2 in Mvc 5

I've got it configured to redirect to login on cookie expiration , which is does next time you refresh.

using System;
using System.Configuration;
using System.Security.Policy;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;

namespace StudentPortalGSuite
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            Int64 cookieDurInMin = 1;
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                SlidingExpiration  = true,
                ExpireTimeSpan     = TimeSpan.FromMinutes( cookieDurInMin ),// How long to leave a "remember me" cookie valid - EWB
                CookieName         = "SP3GGS-ID2-cookie",
                //CookieSecure     = CookieSecureOption.Always, // TODO: turn this on for prod/qa so only ssl is allowed - EWB - per https://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
                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.FromSeconds( 30 ),// how often to valdate against ad - EWB
                            regenerateIdentity: ( manager, user ) => user.GenerateUserIdentityAsync( manager )
                    ),
                    OnResponseSignIn = context =>
                    {
                        context.Properties.AllowRefresh = true;
                        context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes( cookieDurInMin );
                    },

            } );            
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);// HERE EWB


            app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "1032371756979-jtllvb3jdo2h2mg4ocr10o20i8il7r8s.apps.googleusercontent.com",
                ClientSecret = "VHUtLlxnB2Zfctp0QyCvu-9X"//,

            } );
        }
    }
}

But i want to detect when it's expired and redirect to login automatically (but i don't want to constantly refresh the page)

Is there a clever way to do this?

Thanks,

Eric-

Upvotes: 3

Views: 2774

Answers (1)

Horkrine
Horkrine

Reputation: 1407

Pretty much every modern browser will delete a cookie when it is expired. If you set a session cookie, it will never expire until you tell it to. Lets pretend a user logs in and their cookie lasts for 1 hour. In 1 hour, the cookie's ExpireTimeSpan value will be less than the current system's DateTime, so the browser will delete the cookie. The user will not have a session cookie anymore and will need to log back in. Try it for yourself!

If you want to detect whether or not the user was logged in, you could set a second unrelated Session cookie saying that the user HAD a session. Do not store any other information in the cookie. Let's call this a 'Flag' cookie.

If the Flag cookie exists but the actual Login cookie does not, you can redirect to the login page and inform them that their login session has expired. I'd be sure to delete the cookie once you get there too so that every time they load a page they aren't redirected to login. It's a quick and dirty way of doing it, but it works just fine.


Here's a test example for you. Try adding this code in to create a cookie and watch it delete itself after 1 minute:

var timedCookie = new HttpCookie("timedCookie")
{
    Value = "Timed cookie",
    Expires = DateTime.Now.AddMinutes(1)
};

Response.Cookies.Add(timedCookie);

This is how I view the cookie in Chrome. If you don't use Chrome, you'll have to look at how to do this in whatever browser you use:

Once you've ran the code to get the cookie, you can press F12 to open up the developer console. From here, click Application in the top bar and then select Cookies in the sidebar. Select the one that relates to the website (normally first in the list) and you'll see your cookie. Wait for around 1-2 minutes so that the time has definitely passed. You should be able to refresh and watch your browser delete the cookie

Upvotes: 1

Related Questions