.NET Core 3.1 & Identity 问题(声明名称标识符的 ID 与任何用户都不匹配,而声明名称是正确的)



我在网站的一个区域遇到问题,我需要检索用户Id,我使用HttpContext.user和注入的IHttpContextAccessor尝试了这两种方法,都给了我一个Id,1(与用户不匹配,2(甚至不存在于我的数据库中!

我还尝试注入UserManager并对其调用GetUserId,这也给了我错误的id(再一次,不知道从哪里来,它不在数据库中(。对其调用GetUserAsync返回null。

我没有使用任何特别或花哨的东西,idendity核心中包含的默认页面来登录,只是一个从IdentityDbContext继承的上下文,登录部分工作得很好,因为这些页面位于Authorize标记后面,确实迫使我登录。如果我一开始就犯了一个错误,我可以挖,但我只是得到了一个似乎不知从哪里来的Id,不知道该去哪里找。

以下是呼叫时的索赔情况

HttpContext.User.Claims.ToList()
[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: f478bf7a-1734-494c-aad6-0882ab24007f} <-- this id is not present in AspNetUsers table
[1]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: EDITED OUT FOR PRIVACY} <-- my correct username (my email)
[2]: {AspNet.Identity.SecurityStamp: EDITED OUT}
[3]: {http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Administrator} <-- correctly finds my role too

您可以使用以下代码来获取UserId

using System.Security.Claims;

using Microsoft.AspNetCore.Identity;


var claimsIdentity = (ClaimsIdentity)this.User.Identity;

var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);

var userId = claim.Value;

我在ExternalLoginCallback:中使用它时遇到了这个问题

var user = new SmileAppUser { UserName = email, Email = email };
await _signInManager.SignInAsync(user, isPersistent: false);

尝试从数据库中检索用户,以将id包含在具有SignInAsync的声明中。

最新更新