【发布时间】:2016-03-28 21:45:42
【问题描述】:
我正在通过 OWIN 中间件使用 ASP.NET Identity 2 身份验证。我使用模板创建了一个新项目,因此最初从默认生成的代码开始,但对其进行了一些更改(取出实体框架并连接到我自己现有的身份验证中)。这一切正常。
我现在想做的是在用户通过保存的 cookie 登录后执行代码。我查看了 Startup.Auth.cs 文件中的 ConfigureAuth,配置如下:
public void ConfigureAuth(IAppBuilder app) {
// Configure the user manager and signin manager to use a single instance
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"),
Provider = new CookieAuthenticationProvider {
OnResponseSignIn = ctx => {
Log.Trace("On Response Sign In.");
},
OnResponseSignedIn = ctx => {
Log.Trace("On Response Signed In.");
},
OnValidateIdentity = async ctx => {
Log.Trace("On Validate Identity.");
}
}
});
}
从这里我可以看到 OnResponseSignIn 和 OnResponseSignedIn 只有在用户输入用户名和密码的实际登录期间才会被命中。当用户通过保存的 cookie 进行身份验证时,它们不会被命中。
无论用户是通过用户名/密码还是保存的 cookie 进行身份验证,都会命中 OnValidateIdentity,并且会针对他们发出的每个请求进行命中。
我想要的是在通过 cookie 登录后只执行一次代码。有谁知道如何做到这一点?如果不是,我想另一种选择是将代码放在 OnValidateIdentity 但在 if 语句中,这将阻止它运行,除非它是在 cookie 身份验证后的第一次调用。谁能想到如何实现这一目标?我能想到的就是在代码第一次运行后在 Session 中设置一个变量并检查它是否存在以防止它重新运行?
【问题讨论】:
-
您的任务问题是“通过 cookie 登录后只执行一次代码”。什么是“通过 cookie 登录”?我怀疑你想知道用户是否有一个持久的 cookie 并在一些不活动后回到你的网站。但什么是“不活动”? 5 分钟足以有资格不活动吗? 24小时呢? 48小时?一旦你定义了这个,我可能会告诉你在哪里看。
-
@trailmax 感谢并为延迟道歉。是的,你一针见血:如果他们有一个持久的cookie。基本上,如果他们在没有 cookie 的情况下访问该站点,他们会输入他们的用户名和密码,我就可以进入该过程。问题是当他们带着持久性 cookie 回来时。本质上,我希望代码在他们回来并开始新会话时运行,无论它已经过了多长时间。 IE。如果他们回来,提供 cookie 并且应用程序让他们进入,在回避输入用户名和密码后,我想要一些代码运行。再次感谢!
-
@Kiquenet 抱歉,我想我没有。
标签: asp.net asp.net-mvc asp.net-identity