繁体   English   中英

ASP.NET Identity 2 在 cookie 身份验证后执行代码

[英]ASP.NET Identity 2 execute code after cookie authentication

我正在通过 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 中设置一个变量并检查它是否存在以防止它重新运行?

它可能可以通过使用会话变量作为标志来完成,并且仅在未设置时执行您的操作。

OnValidateIdentity = async context => {
    if (HttpContext.Current.Session["Refreshed"] == null)
    {
        /** do your thing **/
        ...

        HttpContext.Current.Session["Refreshed"] = new object();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM