我的 ASP.NET Core 2.1.0 MVC 网站上发生了一些相当可怕的事情。当我浏览时,突然显示我以其他用户身份登录(当时也恰好在浏览该网站)。
我无法确定是否有特定的用例触发此问题,但这种情况现在已经发生了两次。导航到其他页面仍然显示我以其他用户身份登录。甚至看起来我接管了我错误登录的用户的声明。
我的问题是:什么会导致这种情况发生?
编辑:我已将 userManager
和 notificationService
更改为“范围”,并且此问题再次发生,因此此处报告的潜在问题无法成为原因。
试图调查这一点,我相信罪魁祸首可能是 _Layout.cshtml
中的以下调用:
@inject UserManager<ApplicationUser> userManager
@inject NotificationService notificationService
@inject CommunityService communityService
@{
ApplicationUser user = await userManager.GetUserAsync( User );
}
返回的user
用于显示用户信息并调用notificationService
和communityService
。这些还显示了与错误(不是我)用户相关的数据。
如果重要的话,这就是在 Startup.cs
中设置 ApplicationDbContext
的方式:
// Add framework services.
services
.AddDbContext<ApplicationDbContext>( options => options
.UseLazyLoadingProxies()
.UseSqlServer(_configuration.GetConnectionString( "DefaultConnection" ) ) );
services
.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
我记得'scoped' is the recommended lifetime to use when registering Entity Framework for dependency injection 。不过,NotificationService
和 CommunityService
都注册为“ transient ”,并通过构造函数注入(inject)请求 ApplicationDbContext
来访问数据。
services.AddTransient<CommunityService, CommunityService>();
services.AddTransient<NotificationService, NotificationService>();
这可能有什么关系吗?目前,我不明白这是否会产生任何影响。我似乎无法复制这个问题。
最佳答案
好消息!这是我自己造成的(我相信,请阅读下面的详细信息帮助我解决这个问题)。因此,您可以放心,除非您犯了与我相同的错误,否则 ASP MVC 身份验证机制不应该归咎于此(至少,这是我目前的理解)。
我将记录我到底做错了什么,以及如何复制,因为其他人可能会犯同样的错误。
简而言之:我调用了 SignInManager<TUser>.RefreshSignInAsync(TUser)
使用“错误”用户(我最终登录的用户),导致我以该用户身份登录。
我为什么这样做?在我的特定用例中,我想根据当前登录用户的操作向其他用户发出声明。因此我调用:
await _userManager.AddClaimAsync( userToGiveClaim, newClaim );
await _signInManager.RefreshSignInAsync( userToGiveClaim );
我调用了RefreshSignInAsync
因为我想防止收到声明的用户必须注销并登录才能使新声明生效。来自 the RefreshSignInAsync
documentation我的印象是这应该有效:
Regenerates the user's application cookie, whilst preserving the existing AuthenticationProperties like rememberMe, as an asynchronous operation.
Parameters user The user whose sign-in cookie should be refreshed.
我仍然不完全清楚为什么触发此调用时当前登录的用户会获取传递给此调用的用户的身份。这仍然不是我理解文档的方式( I filed this as a bug report ),但由于这是可重现的,我现在更倾向于相信我只是误解了文档。
关于asp.net-core - 什么可能导致 `UserManager` 返回错误的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51571852/