如果用户使用ASP .Net Identity通过外部登录提供商登录,如何保存上次登录日期?

问题描述 投票:7回答:2

我用AspNetUser属性扩展了LastLoginDate类,以记住用户每次登录时的情况。

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

每次用户使用电子邮件和密码作为登录凭据进行常规登录时,登录都可以正常工作。在AccountController中,我有登录操作:

[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只是一个扩展方法,它基本上只是将当前时间设置为用户LastLoginDate属性:

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

但是当我像下面这样进行外部登录时:

[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" ...) 
     }

     ...
}

在这种情况下如何记录用户登录日期?我目前没有诸如emailId之类的有关用户的信息,以使他与UserManager保持一致。我已经尝试过:User.Identity.GetUserId<int>()Id之后获得用户SignInManager.ExternalSignIn(loginInfo),但登录后未更新,它仍然是default(int)-0SignInStatus只是一个enum,没有有关已登录用户的其他信息,也不能选择使用ExternalLoginInfo.Email,因为该电子邮件可能与用户的实际注册电子邮件不同。

c# asp.net asp.net-mvc login asp.net-identity
2个回答
4
投票

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


0
投票

@@ Dmytro,能否请您在"public static IdentityResult RememberLoginDate(this ApplicationUserManager manager, User user)"所在的位置共享文件我需要知道该部分放在AccountController文件中的位置的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.