title: ASP.NET Identity 2 execute code after cookie authentication
body: <p>I'm using ASP.NET Identity 2 authentication via OWIN middlewear.  I've created a new project using the template so initially started with the default generated code but have changed it a bit (taken out entity framework and wired in my own existing authentication).  This is all working.</p>
  
  <p>What I'd now like to do is execute code after a user logs in via a saved cookie.  I've had a look at ConfigureAuth in the Startup.Auth.cs file which I've configured as follows:</p>
  
  <pre><code>    public void ConfigureAuth(IAppBuilder app) {
  
          // Configure the user manager and signin manager to use a single instance
          app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
          app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;(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 =&gt; {
                      Log.Trace("On Response Sign In.");
                  },
                  OnResponseSignedIn = ctx =&gt; {
                      Log.Trace("On Response Signed In.");
                  },
                  OnValidateIdentity = async ctx =&gt; {
                      Log.Trace("On Validate Identity.");
                  }
              }
          });            
  
      }
  </code></pre>
  
  <p>From this I can see that OnResponseSignIn and OnResponseSignedIn are hit only during actual logins when the user enters their username and password.  They are not hit when the user is authenticated via saved cookie.</p>
  
  <p>OnValidateIdentity is hit regardless of whether the user authenticated via username/password or saved cookie and it's hit for every request they make.</p>
  
  <p>What I'd like is to execute code just once after a login via cookie.  Does anyone know how to do this?  If not, I guess another option is to put code in OnValidateIdentity but in an if statement that will prevent it being run unless its the first call after the cookie authentication.  Can anyone think of how to achieve that?  All I can think of is to set a variable in Session after the code is first run and check for it's presence to prevent it being re-run?</p>