简体   繁体   中英

How to save user last login date if he was logged in with external login provider using ASP .Net Identity?

I've extended AspNetUser class with LastLoginDate property to remember each time user makes login.

public sealed partial class User : IdentityUser<int, UserLogin, UserRole, UserClaim>, IUser<int>, IDatabaseEntity
{
    ...
    public DateTime? LastLoginDate { get; set; }   
}

Loging works fine each time user makes usual login using email and password as login credentials. In AccountController I have my login action:

[HttpPost]
public ActionResult Login(LoginModel model)
{
    ...
    var result = SignInManager.PasswordSignIn(model.Email, model.Password, model.RememberMe);

    if (result == SignInStatus.Success)
    {
        var user = UserManager.FindByEmail(email);
        UserManager.RememberLoginDate(user);  
        return Redirect(model.ReturnUrl);
    }

    ...
}

RememberLoginDate is just an extension methods which basically just sets current time to user LastLoginDate property:

public static IdentityResult RememberLoginDate(this ApplicationUserManager manager, User user)
{
     user.LastLoginDate = DateTime.UtcNow;;
     return manager.Update(user);
}

But when I do external login like below:

[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl, string provider)
{
     var loginInfo = AuthenticationManager.GetExternalLoginInfo();
     if (loginInfo == null)
          return RedirectToAction("ExternalLoginFail");

     // Sign in the user with this external login provider if the user already has a login
     var result = SignInManager.ExternalSignIn(loginInfo);
     if (result == SignInStatus.Success)
          return RedirectToLocal(returnUrl);

     if (result == SignInStatus.Failure)
     {
          return View("ExternalLoginConfirmation" ...) 
     }

     ...
}

How can I log user login date in this case? I have no info about the user such as email or Id to get him with UserManager at this point. I've already tried: User.Identity.GetUserId<int>() to get user Id after SignInManager.ExternalSignIn(loginInfo) but it is not updated after login, it still is default(int) - 0 . SignInStatus is just an enum with no additional info about the logged user and use ExternalLoginInfo.Email is also not an option because this email can be different from user's actual registered email.

您应该能够使用UserManager.FindAsync(loginInfo.Login)通过提供程序和密钥拉回您的用户 - 这就是 SignInManager 本身的工作方式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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