locked
How to save a "LastLoggedIn" date when user logs in using Token based authentication? RRS feed

  • Question

  • User-1204646426 posted

    Hello, to save the date and time when user logs in, I have do this in GrantResourceOwnerCredentials of my custom 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;
                }
    
                if (user.Locked)
                {
                    context.SetError("invalid_grant", "El usuario está bloqueado. Contáctese con el administrador.");
                    return;
                }
    
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                   OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                    CookieAuthenticationDefaults.AuthenticationType);
    
                oAuthIdentity.AddClaim(new Claim("LastLoggedOn", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")));
    
                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }

    As you see, I am adding a claim, but by doing this, no actual user update occurs.

    how can I do it?

    Thanks

    Jaime

    Tuesday, December 4, 2018 11:44 PM

All replies

  • User1724605321 posted

    Hi jstuardo ,

    In your scenario , you just add claim to user's claim ,so that the client/resource could access the claim like :

    ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "LastLoggedOn").Value;

    That is not related to update/insert that value to your database . If you want to save the LastLoggedOn properties in your database , you should add logic to update related database table using EF :

    https://stackoverflow.com/a/40579369/5751404 

    Best Regards,

    Nan Yu

    Thursday, December 6, 2018 3:13 AM
  • User-1204646426 posted

    Hello Nan Yu,

    that StackOverflow question is not related to my problem. It just explains how to add a new field that is populated when registering.

    That is not my problem since I can perfectly add custom fields and populate and in fact, my SQL Server table is not the default AspNetUsers table but a completely custom table called "Usuarios".

    My problem is related to update certain field (in this case LastLoggedIn field) just after login. None of my custom methods to update a user is called when user is logged in, so that is the question.

    When GrantResourceOwnerCredentials method of my custom AuthProvider returns after user authenticated, it returns the token to the page, but I don't know if there is an instance I can use to update the LasttLoggedIn date.

    Since my login is performed by mean of an Ajax call, I am thinking to make a new ajax request to the MVC controller just to update that field, but I think this may be tricky.

    Regards

    Jaime

    Thursday, December 6, 2018 5:14 PM
  • User475983607 posted

    Simply set the LastLoggedIn property, I assume the property exists on the user type and the DB, then save.   The syntax looks similar to...

    user.LastLoggedIn = DateTime.Now
    var result = await userManager.UpdateAsync(user);

    Thursday, December 6, 2018 8:03 PM
  • User-1204646426 posted

    Yes... finally I did this exactly as you wrote:

    user.LastLoggedOn = DateTime.Now;
    await userManager.UpdateAsync(user);

    Thursday, December 6, 2018 9:22 PM
  • User1724605321 posted

    Hi jstuardo ,

    None of my custom methods to update a user is called when user is logged in, so that is the question.

    As i said , none of your codes are related to the database operation , you should update the property in database using EF , i assume you haven't added the column in user table , so i provide the SO thread link to help you make the migration , After that , you can use update statement to update related column .

    Best Regards,

    Nan Yu

    Friday, December 7, 2018 2:01 AM
  • User-1204646426 posted

    Nan Yu,

    I have finally used mgebhard suggestion. It was as simple as adding the update line in GrantResourceOwnerCredentials method of authorization provider.

    Regards

    Jaime

    Friday, December 7, 2018 6:59 PM