How to know when OWIN cookie will expire?

All you need is to get hold of the CookieValidateIdentityContext during the cookie validation stage. Once you get it, extract whatever you need and keep them as Claim or some other way that you prefer.

For MVC 5 with Asp.NET Identity 2.0, you need to perform two steps:

  1. Define custom OnValidateIdentity, extract cookie information, and keep it as Claim.

    public class Startup
    {
      public void Configuration(IAppBuilder app)
      {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
          AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
          Provider = new CookieAuthenticationProvider
          {
            OnValidateIdentity = MyCustomValidateIdentity //refer to the implementation below
          }
        }
      }
    
    
      // this method will be called on every request
      // it is also one of the few places where you can access unencrypted cookie content as CookieValidateIdentityContext
      // once you get cookie information you need, keep it as one of the Claims
      // please ignore the MyUserManager and MyUser classes, they are only for sample, you should have yours
      private static Task MyCustomValidateIdentity(CookieValidateIdentityContext context)
      {
        // validate security stamp for 'sign out everywhere'
        // here I want to verify the security stamp in every 100 seconds.
        // but I choose not to regenerate the identity cookie, so I passed in NULL 
        var stampValidator = SecurityStampValidator.OnValidateIdentity<MyUserManager<Myuser>. MyUser>(TimeSpan.FromSeconds(100), null); 
        stampValidator.Invoke(context);
    
        // here we get the cookie expiry time
        var expireUtc = context.Properties.ExpiresUtc;
    
        // add the expiry time back to cookie as one of the claims, called 'myExpireUtc'
        // to ensure that the claim has latest value, we must keep only one claim
        // otherwise we will be having multiple claims with same type but different values
        var claimType = "myExpireUtc";
        var identity = context.Identity;
        if(identity.HasClaim(c=> c.Type == claimType))
        {
          var existingClaim = identity.FindFirst(claimType);
          identity.RemoveClaim(existingClaim); 
        }
        var newClaim = new Claim(claimType, expireUtc.Value.UtcTicks.ToString());
        context.Identity.AddClaim(newClaim);
    
        return Task.FromResult(0);
      }
    }
    
  2. Access your Claim in your controller methods

    // since expiry time has now become part of your claims, you now can get it back easily
    // this example just returns the remaining time in total seconds, as a string value
    // assuming this method is part of your controller methods
    
    public string RemainingTime()
    {
      var identity = User.Identity as ClaimsIdentity;
      var claimType = "myExpireUtc";  //NOTE: must be the same key value "myExpireUtc" defined in code shown above
    
      if(identity != null && identity.HasClaim(c=> c.Type == claimType))
      { 
        var expireOn = identity.FindFirstValue(claimType); 
    
        DateTimeOffset currentUtc = DateTimeOffset.UtcNow;
        DateTimeOffset? expireUtc = new DateTimeOffset(long.Parse(expireOn), TimeSpan.Zero);
    
        var remaining = (expireUtc.Value - currentUtc).TotalSeconds;
    
        return remaining.ToString();
      }
      return string.Empty;
    }
    

I use this approach to remind my application users to extend their session before session time out.

Credit to this post How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?


I just want to build on the first answer, i had problems getting it to work as i was using a custom user store. though the implementation seems simpler for myself

public static class ApplicationCookieValidateIdentityContext
    {
        public static Task ApplicationValidateIdentity(CookieValidateIdentityContext context)
        {          
            var identity = context.Identity;

            if (identity.HasClaim(c => c.Type ==  "expires"))
            {
                var existingClaim = identity.FindFirst( "expires");
                identity.RemoveClaim(existingClaim);
            }

            if (context.Properties.ExpiresUtc == null) return Task.FromResult(0);

            context.Identity.AddClaim(new Claim("expires", context.Properties.ExpiresUtc.ToString()));

            return Task.FromResult(0);
        }
    }

I also created a filter that adds the expiration to a cookie

// make sure its defaulted because the claim is not set on the login callback
var expires = DateTimeOffset.Now.AddMinutes(
    Convert.ToDouble(ConfigurationManager.AppSettings["SessionTimeInMinutes"]));


if (identity.HasClaim(c => c.Type == "expires"))
{
    expires = DateTimeOffset.Parse(identity.FindFirstValue("expires"));
}

cookieHeaderValues.Add(new SessionCookeHeaderValue("expiresAt", expires.ToString("O"), expires));


Comments

  1. Bellamy

    • 2015/1/2

    All you need is to get hold of the CookieValidateIdentityContext during the cookie validation stage. Once you get it, extract whatever you 

  2. Dupont

    • 2016/3/24

    MyUser>(TimeSpan.FromSeconds(100), null); stampValidator.Invoke(context); // here we get the cookie expiry time var expireUtc = context.Properties.ExpiresUtc; // add the expiry time back to cookie as one of the claims, called 'myExpireUtc' // to ensure that the claim has latest value, we must keep only one claim // otherwise we will be having multiple claims with same type but different values var claimType = "myExpireUtc"; var identity = context.Identity; if(identity.HasClaim(c=> c.Type

  3. Jasiah

    • 2017/3/27

    How to know when OWIN cookie will expire? Solution: All you need is to get hold of the CookieValidateIdentityContext during the cookie validation stage. Once 

  4. Armando

    • 2020/10/9

    By default, the expiration is set to 24h. How to adjust the expiration of it. It is in plain ASP.NET Identity fairly simple to set, through your Startup (via OWIN). Optimizely has though not made it as obvious, due to the introduction of non-configurable AddCmsAspNetIdentity middleware.

  5. Knox

    • 2017/4/19

    Again, the cookie stays around for the default 14 days but the ticket inside the cookie will expire in 7 days. The reference documentation 

  6. Carter

    • 2018/3/17

    And if I comment above ExpireTimeSpan from startup class then it considers default 14 days but not the 7 days defined in AuthenticationProperties. Again, the cookie stays around for the default 14 days but the ticket inside the cookie will expire in 7 days. The reference documentation explains the details. https://msdn.microsoft.com/en-us/library/microsoft.owin.security.authenticationproperties (v=vs.113).aspx.

  7. Khalil

    • 2020/4/26

    However, let's suppose, Sliding expiration is true [by default]. What would happen then? The cookie would be regenerated on any request within 

  8. Ira

    • 2017/9/15

    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.

  9. Luka

    • 2021/1/15

    Using something like SignalR you could check to see if the clients can still actively respond after authentication (pick some arbitrary time interval). If the 

  10. Leonardo

    • 2020/12/22

    The Katana cookie authentication middleware supports either a sliding or an absolute expiration, but not both. Recently a client was interested in having both, so I decided to figure out how this could be done.

  11. Misael

    • 2016/9/16

    In order to notify the user I need to know when the cookie is about to expire. I've tried using the OnValidateIdentity method as per this question, 

  12. Zakai

    • 2019/12/24

    How to know when OWIN cookie will expire? .net asp.net-mvc-5 session-cookies owin asked Apr 15 '14 at 17:37 stackoverflow.com

  13. Kabir

    • 2018/5/14

    To sum up, I would like to know why setting o.SlidingExpiration = true (EDITED) does not recreate the cookie with a new expiration when 

  14. Laurent

    • 2016/7/6

    The expiration information is in the protected cookie ticket. OWIN Authentication, ExpireTimeSpan not working, The SlidingExpiration is set to true to instruct the middleware to re-issue a Owin .Security.Cookies (in Microsoft.Owin.Security.Cookies.dll) The SlidingExpiration is set to true to instruct the middleware to re-issue a new cookie with a new expiration time any time it processes a request which is more than halfway through the expiration window. Namespace: Microsoft.Owin.Security

  15. Roberts

    • 2019/7/16

    When the cookie expires, the user will be redirected to the logon page. What happens when the The forms authentication ticket is used to tell the ASP.

  16. Axel

    • 2020/9/15

    Check the Microsoft Product Lifecycle for information about how this Because of that an expired cookie will be ignored even if it is 

Comments are closed.

Recent Posts