【问题标题】:Asp.Net Identity2, How to detect when the cookie expiresAsp.Net Identity2,如何检测 cookie 何时过期
【发布时间】:2018-05-29 03:11:02
【问题描述】:

我在 Mvc 5 中使用 Identty 2

我已将其配置为在 cookie 过期时重定向到登录,下次刷新时会这样做。

using System;
using System.Configuration;
using System.Security.Policy;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;

namespace StudentPortalGSuite
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            Int64 cookieDurInMin = 1;
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                SlidingExpiration  = true,
                ExpireTimeSpan     = TimeSpan.FromMinutes( cookieDurInMin ),// How long to leave a "remember me" cookie valid - EWB
                CookieName         = "SP3GGS-ID2-cookie",
                //CookieSecure     = CookieSecureOption.Always, // TODO: turn this on for prod/qa so only ssl is allowed - EWB - per https://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromSeconds( 30 ),// how often to valdate against ad - EWB
                            regenerateIdentity: ( manager, user ) => user.GenerateUserIdentityAsync( manager )
                    ),
                    OnResponseSignIn = context =>
                    {
                        context.Properties.AllowRefresh = true;
                        context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes( cookieDurInMin );
                    },

            } );            
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);// HERE EWB


            app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "1032371756979-jtllvb3jdo2h2mg4ocr10o20i8il7r8s.apps.googleusercontent.com",
                ClientSecret = "VHUtLlxnB2Zfctp0QyCvu-9X"//,

            } );
        }
    }
}

但我想检测它何时过期并自动重定向到登录(但我不想不断刷新页面)

有没有聪明的方法来做到这一点?

谢谢,

埃里克-

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-5 asp.net-identity-2


【解决方案1】:

几乎每个现代浏览器都会在 cookie 过期时删除它。如果你设置了一个会话 cookie,它永远不会过期,直到你告诉它。让我们假设用户登录并且他们的 cookie 持续 1 小时。 1 小时后,cookie 的 ExpireTimeSpan 值将小于当前系统的 DateTime,因此浏览器将删除 cookie。用户将不再拥有会话 cookie,需要重新登录。自己试试吧!

如果您想检测用户是否登录,您可以设置第二个不相关的会话 cookie,说明用户有一个会话。不要在 cookie 中存储任何其他信息。我们称其为“标志”cookie。

如果存在标志 cookie 但实际登录 cookie 不存在,您可以重定向到登录页面并通知他们他们的登录会话已过期。一旦你到达那里,我一定会删除 cookie,这样每次他们加载页面时,他们都不会被重定向到登录。这是一种快速而肮脏的方式,但效果很好。


这是为您准备的测试示例。尝试添加此代码以创建一个 cookie,并观察它在 1 分钟后自行删除:

var timedCookie = new HttpCookie("timedCookie")
{
    Value = "Timed cookie",
    Expires = DateTime.Now.AddMinutes(1)
};

Response.Cookies.Add(timedCookie);

这就是我在 Chrome 中查看 cookie 的方式。如果您不使用 Chrome,则必须查看如何在您使用的任何浏览器中执行此操作:

运行代码获取 cookie 后,您可以按 F12 打开开发者控制台。在此处,单击顶部栏中的应用程序,然后在侧栏中选择 Cookies。选择与网站相关的那个(通常是列表中的第一个),您会看到您的 cookie。等待大约 1-2 分钟,这样时间肯定已经过去了。您应该能够刷新并看到您的浏览器删除 cookie

【讨论】:

  • 如果我错了,请原谅,但这不适用于滑动到期,对吧?
猜你喜欢
  • 2017-12-02
  • 2011-06-19
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2012-07-25
  • 2010-09-05
相关资源
最近更新 更多