代码之家  ›  专栏  ›  技术社区  ›  jstuardo

使用时在哪里可以设置上次登录时间ASP.NET奥温呢?

  •  0
  • jstuardo  · 技术社区  · 7 年前

        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);
        }
    

    此时,我无法访问名为“lastLoginAt”的字段所在的用户表。我需要将该字段更新为用户登录的日期和时间。

    我还有一个自定义用户存储,它有一个这样定义的方法:

    public Task UpdateAsync(T user)
    

    但如果必须更新用户实体,则会调用该方法。

    您建议在哪里添加代码来更新上次登录的日期和时间?

    1 回复  |  直到 7 年前
        1
  •  0
  •   klitz    7 年前

    至于我,我是这样用的。

    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;
            }
        }
    

    您可以修改 ClaimsIdentity oAuthIdentity ClaimsIdentity .