Owin Cookie身份验证的访问ExpireTimeSpan物业通知登录到期的用户 [英] Access ExpireTimeSpan property of Owin Cookie Authentication to notify user of login expiry

查看:432
本文介绍了Owin Cookie身份验证的访问ExpireTimeSpan物业通知登录到期的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Owin的Cookie认证闲置一段时间后注销用户。关键是,我需要让用户知道他们的会议'X'分钟后过期。

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.

如何访问身份验证cookie获取的剩余时间?这甚至可能?有没有人有之前做这样的事情?

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?

推荐答案

这是可能的。要做到这一点的一种方法是使用 OnValidateIdentity 回调,这就是所谓的每一个cookie将被验证的时间,这是每一个请求到Web应用进行时间(假设活动模式)。

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

在这里,我存储剩余OWIN环境字典秒。你可以用它从任何地方的字典访问并通知用户。例如,从一个MVC控制器,你可以做这样的事情。

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

这篇关于Owin Cookie身份验证的访问ExpireTimeSpan物业通知登录到期的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆