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

前端 未结 1 1339
刺人心
刺人心 2021-01-03 01:15

I am using Owin\'s cookie authentication to logout users after a time period of inactivity. The thing is, I need to let the user know that their session expires in \'X\' min

1条回答
  •  梦毁少年i
    2021-01-03 01:35

    It is possible. One way to do that would be to use the OnValidateIdentity callback, which is called every time the cookie is authenticated, which is every time a request is made to the web app (assuming 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("time.Remaining", 
                       context.Properties.ExpiresUtc.Value.Subtract(now).TotalSeconds);
    
                return Task.FromResult(null);
            }
        }
    };
    
    app.UseCookieAuthentication(options);
    
    
    

    Here, I'm storing the seconds remaining in OWIN environment dictionary. You can use it from anywhere the dictionary is accessible and inform the user. For example, from an MVC controller, 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();
        }
    }
    

    0 讨论(0)
    提交回复
    热议问题