我正在为我的 asp.net core API 使用 IdentityServer 4(带有 sql 存储)。我想在数据库中的某个位置添加一个“上次访问”字段,该字段可用于在用户搜索端点中对我的用户类型之一进行排序。理想情况下,这将显示他们上次在系统中执行操作的时间。
如果我在登录方法中执行此操作,它将不准确,因为它只会在最初生成令牌时更新。我可以向用户访问的每个端点添加一个方法,但这感觉不是正确的解决方案,因为它会重复我自己。
维护记录用户上次访问系统时间的数据库字段的正确位置和方法是什么?
为了记录用户的活跃时间,您可以尝试中间件,它将为每个请求调用。
以下是步骤。
1.在ApplicationUser中添加字段,存储最后访问时间
public class ApplicationUser : IdentityUser
{
public DateTime LastAccessed { get; set; }
}
2.运行命令添加迁移 LastAccessed and 更新数据库
3.添加中间件根据用户名更新上次访问时间
app.UseAuthentication();
app.Use(async (context, next) => {
await next.Invoke();
//handle response
//you may also need to check the request path to check whether it requests image
if (context.User.Identity.IsAuthenticated)
{
var userName = context.User.Identity.Name;
//retrieve uer by userName
using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
{
var user = dbContext.ApplicationUser.Where(u => u.UserName == userName).FirstOrDefault();
user.LastAccessed = DateTime.Now;
dbContext.Update(user);
dbContext.SaveChanges();
}
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)