Access ExpireTimeSpan Owin Cookie Authentication property to notify the user of registration completion

I use Owin cookie authentication to log out after a period of inactivity. The fact is that I have to tell the user that their session expires in "X" minutes.

How can I access the authentication cookie to get the remaining time? Is it possible? Has anyone had to do something like this before?

+4
source share
1 answer

It is possible. One way to do this is to use a callback OnValidateIdentitythat is called every time a cookie is authenticated, that every time a request is made in a web application (subject to active mode).

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);

Here I save the seconds remaining in the OWIN environment dictionary. You can use it from any place where the dictionary is available, and inform the user. For example, from an MVC, you can do something like this.

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

        // Do what you want to do with the secondsRemaining here...

        return View();
    }
}
+6
source

All Articles