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

标签 asp.net asp.net-mvc asp.net-identity

我正在通过 OWIN 中间件使用 ASP.NET Identity 2 身份验证。我使用该模板创建了一个新项目,因此最初使用默认生成的代码开始,但对其进行了一些更改(取出 Entity Framework 并连接到我自己现有的身份验证中)。这一切正常。

我现在想做的是在用户通过保存的 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 中设置一个变量并检查它是否存在以防止它被重新运行?

最佳答案

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

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

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

关于ASP.NET Identity 2 在 cookie 身份验证后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419046/

相关文章:

asp.net - 如何将我的 ASP.NET 成员(member)数据库从 Express 更改为标准 SQL?

asp.net - IdentityServer4 中的 Cookie

asp.net - 如何在同一服务器上托管 Web 应用程序和 API,同时将它们分开?

javascript - javascript 中的 asp.net MVC 表单验证

asp.net - ASP.NET Core Web API 模板中没有个人用户帐户身份验证选项

javascript - 如何知道JS文件中的 Action 类型

javascript - 将 int 数组从 js 发送到 Controller

c# - 过程或函数 SpAddDepartment 指定的参数过多

architecture - 将用户数据存储在身份验证服务器或资源服务器中?或两者?

c# - AddToRole() 方法不会导致 ASP.NET Identity 中的数据库条目