Where can I set last login time when using ASP.NET and Owin?












0















I have implemented authentication using ASP.NET identity. The login is actually performed in this method of the OAuthAuthorizationServerProvider:



    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
return;
}

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);

AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}


At that point, I don't have access to the User table where a field called "lastLoginAt" exists. I need to update that field to the date and time when the user logged in.



I have also a custom user store which has a method defined this way:



public Task UpdateAsync(T user)


but that method will be called if the User entity has to be updated.



Where do you suggest to add the code to update the last login date and time?










share|improve this question



























    0















    I have implemented authentication using ASP.NET identity. The login is actually performed in this method of the OAuthAuthorizationServerProvider:



        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

    ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

    if (user == null)
    {
    context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
    return;
    }

    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
    OAuthDefaults.AuthenticationType);
    ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
    CookieAuthenticationDefaults.AuthenticationType);

    AuthenticationProperties properties = CreateProperties(user.UserName);
    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
    context.Validated(ticket);
    context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }


    At that point, I don't have access to the User table where a field called "lastLoginAt" exists. I need to update that field to the date and time when the user logged in.



    I have also a custom user store which has a method defined this way:



    public Task UpdateAsync(T user)


    but that method will be called if the User entity has to be updated.



    Where do you suggest to add the code to update the last login date and time?










    share|improve this question

























      0












      0








      0








      I have implemented authentication using ASP.NET identity. The login is actually performed in this method of the OAuthAuthorizationServerProvider:



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
      {
      var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

      ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

      if (user == null)
      {
      context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
      return;
      }

      ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
      OAuthDefaults.AuthenticationType);
      ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
      CookieAuthenticationDefaults.AuthenticationType);

      AuthenticationProperties properties = CreateProperties(user.UserName);
      AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
      context.Validated(ticket);
      context.Request.Context.Authentication.SignIn(cookiesIdentity);
      }


      At that point, I don't have access to the User table where a field called "lastLoginAt" exists. I need to update that field to the date and time when the user logged in.



      I have also a custom user store which has a method defined this way:



      public Task UpdateAsync(T user)


      but that method will be called if the User entity has to be updated.



      Where do you suggest to add the code to update the last login date and time?










      share|improve this question














      I have implemented authentication using ASP.NET identity. The login is actually performed in this method of the OAuthAuthorizationServerProvider:



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
      {
      var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

      ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

      if (user == null)
      {
      context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
      return;
      }

      ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
      OAuthDefaults.AuthenticationType);
      ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
      CookieAuthenticationDefaults.AuthenticationType);

      AuthenticationProperties properties = CreateProperties(user.UserName);
      AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
      context.Validated(ticket);
      context.Request.Context.Authentication.SignIn(cookiesIdentity);
      }


      At that point, I don't have access to the User table where a field called "lastLoginAt" exists. I need to update that field to the date and time when the user logged in.



      I have also a custom user store which has a method defined this way:



      public Task UpdateAsync(T user)


      but that method will be called if the User entity has to be updated.



      Where do you suggest to add the code to update the last login date and time?







      c# asp.net-mvc asp.net-identity owin






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 23:56









      jstuardojstuardo

      98652860




      98652860
























          1 Answer
          1






          active

          oldest

          votes


















          0














          As for me I used it this way.



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
          var userStore = new UserStore<ApplicationUser>(new ExtractorDbContext());
          var manager = new UserManager<ApplicationUser>(userStore);
          var user = await manager.FindAsync(context.UserName, context.Password);

          if (user != null)
          {
          string roleName = manager.GetRoles(user.Id).FirstOrDefault();

          var identity = new ClaimsIdentity(context.Options.AuthenticationType);
          identity.AddClaim(new Claim("UserId", user.Id));
          identity.AddClaim(new Claim("Username", user.UserName));
          identity.AddClaim(new Claim("Email", user.Email));
          identity.AddClaim(new Claim("FirstName", user.FirstName));
          identity.AddClaim(new Claim("LastName", user.LastName));
          identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
          identity.AddClaim(new Claim("Role", roleName));
          context.Validated(identity);
          }
          else
          {
          return;
          }
          }


          You can modify your ClaimsIdentity oAuthIdentity same way of my ClaimsIdentity.






          share|improve this answer
























          • Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

            – jstuardo
            Nov 22 '18 at 12:16











          • Have you tried to use that function the same line with your ClaimsIdentity?

            – klitz
            Nov 26 '18 at 0:55











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422092%2fwhere-can-i-set-last-login-time-when-using-asp-net-and-owin%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          As for me I used it this way.



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
          var userStore = new UserStore<ApplicationUser>(new ExtractorDbContext());
          var manager = new UserManager<ApplicationUser>(userStore);
          var user = await manager.FindAsync(context.UserName, context.Password);

          if (user != null)
          {
          string roleName = manager.GetRoles(user.Id).FirstOrDefault();

          var identity = new ClaimsIdentity(context.Options.AuthenticationType);
          identity.AddClaim(new Claim("UserId", user.Id));
          identity.AddClaim(new Claim("Username", user.UserName));
          identity.AddClaim(new Claim("Email", user.Email));
          identity.AddClaim(new Claim("FirstName", user.FirstName));
          identity.AddClaim(new Claim("LastName", user.LastName));
          identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
          identity.AddClaim(new Claim("Role", roleName));
          context.Validated(identity);
          }
          else
          {
          return;
          }
          }


          You can modify your ClaimsIdentity oAuthIdentity same way of my ClaimsIdentity.






          share|improve this answer
























          • Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

            – jstuardo
            Nov 22 '18 at 12:16











          • Have you tried to use that function the same line with your ClaimsIdentity?

            – klitz
            Nov 26 '18 at 0:55
















          0














          As for me I used it this way.



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
          var userStore = new UserStore<ApplicationUser>(new ExtractorDbContext());
          var manager = new UserManager<ApplicationUser>(userStore);
          var user = await manager.FindAsync(context.UserName, context.Password);

          if (user != null)
          {
          string roleName = manager.GetRoles(user.Id).FirstOrDefault();

          var identity = new ClaimsIdentity(context.Options.AuthenticationType);
          identity.AddClaim(new Claim("UserId", user.Id));
          identity.AddClaim(new Claim("Username", user.UserName));
          identity.AddClaim(new Claim("Email", user.Email));
          identity.AddClaim(new Claim("FirstName", user.FirstName));
          identity.AddClaim(new Claim("LastName", user.LastName));
          identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
          identity.AddClaim(new Claim("Role", roleName));
          context.Validated(identity);
          }
          else
          {
          return;
          }
          }


          You can modify your ClaimsIdentity oAuthIdentity same way of my ClaimsIdentity.






          share|improve this answer
























          • Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

            – jstuardo
            Nov 22 '18 at 12:16











          • Have you tried to use that function the same line with your ClaimsIdentity?

            – klitz
            Nov 26 '18 at 0:55














          0












          0








          0







          As for me I used it this way.



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
          var userStore = new UserStore<ApplicationUser>(new ExtractorDbContext());
          var manager = new UserManager<ApplicationUser>(userStore);
          var user = await manager.FindAsync(context.UserName, context.Password);

          if (user != null)
          {
          string roleName = manager.GetRoles(user.Id).FirstOrDefault();

          var identity = new ClaimsIdentity(context.Options.AuthenticationType);
          identity.AddClaim(new Claim("UserId", user.Id));
          identity.AddClaim(new Claim("Username", user.UserName));
          identity.AddClaim(new Claim("Email", user.Email));
          identity.AddClaim(new Claim("FirstName", user.FirstName));
          identity.AddClaim(new Claim("LastName", user.LastName));
          identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
          identity.AddClaim(new Claim("Role", roleName));
          context.Validated(identity);
          }
          else
          {
          return;
          }
          }


          You can modify your ClaimsIdentity oAuthIdentity same way of my ClaimsIdentity.






          share|improve this answer













          As for me I used it this way.



          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
          var userStore = new UserStore<ApplicationUser>(new ExtractorDbContext());
          var manager = new UserManager<ApplicationUser>(userStore);
          var user = await manager.FindAsync(context.UserName, context.Password);

          if (user != null)
          {
          string roleName = manager.GetRoles(user.Id).FirstOrDefault();

          var identity = new ClaimsIdentity(context.Options.AuthenticationType);
          identity.AddClaim(new Claim("UserId", user.Id));
          identity.AddClaim(new Claim("Username", user.UserName));
          identity.AddClaim(new Claim("Email", user.Email));
          identity.AddClaim(new Claim("FirstName", user.FirstName));
          identity.AddClaim(new Claim("LastName", user.LastName));
          identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
          identity.AddClaim(new Claim("Role", roleName));
          context.Validated(identity);
          }
          else
          {
          return;
          }
          }


          You can modify your ClaimsIdentity oAuthIdentity same way of my ClaimsIdentity.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 1:31









          klitzklitz

          285




          285













          • Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

            – jstuardo
            Nov 22 '18 at 12:16











          • Have you tried to use that function the same line with your ClaimsIdentity?

            – klitz
            Nov 26 '18 at 0:55



















          • Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

            – jstuardo
            Nov 22 '18 at 12:16











          • Have you tried to use that function the same line with your ClaimsIdentity?

            – klitz
            Nov 26 '18 at 0:55

















          Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

          – jstuardo
          Nov 22 '18 at 12:16





          Thanks... I have done it, but I need to know the other part now. Where does the actual user saving occur? i am using a custom user store. I have placed a breakpoint at UpdateAsync method of the user store that receives the IdentityUser as parameter. My custom IdentityUser contains the LastLoggedOn property but i could not find where i need to implement the actual record persistance to database.

          – jstuardo
          Nov 22 '18 at 12:16













          Have you tried to use that function the same line with your ClaimsIdentity?

          – klitz
          Nov 26 '18 at 0:55





          Have you tried to use that function the same line with your ClaimsIdentity?

          – klitz
          Nov 26 '18 at 0:55


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422092%2fwhere-can-i-set-last-login-time-when-using-asp-net-and-owin%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Futebolista

          Feedback on college project

          Albești (Vaslui)