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

▼魔方 西西 提交于 2019-12-03 20:54:21

问题


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' minutes.

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


回答1:


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<double>("time.Remaining", 
                   context.Properties.ExpiresUtc.Value.Subtract(now).TotalSeconds);

            return Task.FromResult<object>(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();
    }
}


来源:https://stackoverflow.com/questions/27107264/access-expiretimespan-property-of-owin-cookie-authentication-to-notify-user-of-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!