【问题标题】:How to set ASP.NET Identity auth cookie to expire at a particular date and time如何将 ASP.NET 身份验证 cookie 设置为在特定日期和时间过期
【发布时间】:2019-11-13 00:20:26
【问题描述】:

This answer seems pretty comprehensive 但我的应用使用的是ApplicationSignInManager 而不是答案使用的AuthenticationManager,因此它并不真正适用于我的应用。

我正在尝试跟踪我的用户登录(这是一个供客户内部使用的专有网站)。所以客户基本上希望登录像考勤卡一样工作,这样老板就可以看到员工何时进入办公室。

此功能意味着我不能依赖每个 ASP.NET 身份默认行为的持久登录,因为它不允许我控制登录 cookie 是否/何时过期。

我想做的是在每天凌晨 4 点使 cookie 过期,无论何时登录。

因此,limiting the cookie's lifespan in configs 也不能真正满足我的要求。

这是我的登录代码 - 几乎是标准的东西。根据第一个答案,我希望我可以将 cookie 的到期嵌入到 SignIn 方法中,但由于我没有使用 AuthenticationManager 进行登录,因此似乎没有办法做到这一点我当前的代码。

var manager = Context.GetOwinContext().GetUserManager<UserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

// Note that this always persists the login cookie.
var result = signinManager.PasswordSignIn(Email.Text, Password.Text, true, shouldLockout: false);

// Evaluation of result below

如果我需要在此处更改登录方式,那很好;我只需要一些关于进行哪些更改的指导(示例代码会有所帮助)。

提前致谢!

【问题讨论】:

    标签: c# asp.net cookies asp.net-identity-2


    【解决方案1】:

    由于没有人愿意为我的问题做出贡献,我四处尝试了一堆东西并得出了自己的答案:

    似乎limiting the cookie's lifespan in configs 根据我的问题中的链接实际上是要走的路。

    在auth config方法中,我确定now4am tomorrow之间有多少小时,然后我将cookie的ExpireTimeSpan设置为那个。

    public void ConfigureAuth(IAppBuilder app)
    {
        var expiryDate = DateTime.Now.Date.AddDays(1).AddHours(4);
        var ts = expiryDate - DateTime.Now;
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            ExpireTimeSpan = TimeSpan.FromHours(ts.Hours),
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2021-08-03
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      相关资源
      最近更新 更多