3

I am trying to access expiration time on Owin i am using the following example

Access ExpireTimeSpan property of Owin Cookie Authentication to notify user of login expiry

but i cant get to work. I get an error the key, value does exist. I would really appreciate if someone could point me to the right direction thanks.

StartupAuth.cs

     var config1 = 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))

            }
        };

        app.UseCookieAuthentication(config1);
        var options = new CookieAuthenticationOptions
        {
            // usual options such as LoginPath, for example, go here...
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = context =>
                {
                    DateTimeOffset now = DateTimeOffset.UtcNow;

                    context.OwinContext.Request.Set<double>("time.Remaining",
                           context.Properties.ExpiresUtc.Value.Subtract(now).TotalSeconds);

                    return Task.FromResult<object>(null);
                }
            }
        };
        app.UseCookieAuthentication(options);

Controller

  [Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        //var secondsRemaining = (double)Request.GetOwinContext()
        //                            .Environment["time.Remaining"];
       return View();
    }

}
Community
  • 1
  • 1
Milas
  • 347
  • 2
  • 7
  • 16

2 Answers2

1

This answer has an alternative approach of storing the value. It stores it as a claim. You could try this instead: How to know when OWIN cookie will expire?

Ed Greaves
  • 4,807
  • 2
  • 22
  • 19
0

This is working but kind of ugly.. it accounts for the SlidingExpiration logic .. note that the claim is empty on the signin request in my case so i just set it to the sessionTimeInMinutes

SlidingExpiration = true,
CookieName = applicationCookieName,
Provider = new CookieAuthenticationProvider
{
    // Not called on signin
    OnValidateIdentity = context =>
    {
        // this is the last value before ExpireTimeSpan will update and its not reflected here
        var expiresUtc = context.Properties.ExpiresUtc;

        if ( expiresUtc == null)  return Task.FromResult(0);

        var sessionExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(sessionTimeInMinutes);

        var expiresDifferenceSeconds =
            sessionExpiresUtc.ToUnixTimeSeconds() - expiresUtc?.ToUnixTimeSeconds();

        var expires = sessionTimeInMinutes * 60 / expiresDifferenceSeconds < 2
            ? sessionExpiresUtc
            : expiresUtc;

        context.Identity.UpdateClaim(CustomClaimTypes.Expires, expires.ToString());

        return Task.FromResult(0);
    }
}

then i have a filter that adds a expiration cookie that the app uses

DateTimeOffset expires;

if (identity.HasClaim(c => c.Type == CustomClaimTypes.Expires))
{
     expires = DateTimeOffset.Parse(identity.FindFirstValue(CustomClaimTypes.Expires));
}
else
{
    expires = DateTimeOffset.UtcNow.AddMinutes(sessionTimeInMinutes);
}

var cookieHeaderValues = new List<CookieHeaderValue>
{
    new ApplicationCookeHeaderValue("session.expiresAt", expires.ToString("u"), expires),
};

Ricardo Saracino
  • 1,345
  • 2
  • 16
  • 37
  • I like your idea but can you explain this line of code? var expires = sessionTimeInMinutes * 60 / expiresDifferenceSeconds < 2 ? sessionExpiresUtc : expiresUtc; Why "2"? – Cornel Jun 30 '21 at 09:52
  • its been a long time. i think i was just testing with a hardcoded value of 2 min – Ricardo Saracino Jul 02 '21 at 17:33