我有一个 .net 6 Web api,当我尝试使用下面的配置获取当前用户 ID 时,始终返回 null。
//in api controller
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
//in Program.cs
services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
services.AddHttpContextAccessor();
有什么办法可以解决吗?
提前致谢。
最佳答案
既然您配置了 IdentityOptions 选项,我假设您正在使用 Asp.net Core Identity 进行身份验证和授权,对吧?
我创建了一个 Asp.net core 应用程序并使用 Asp.net core Identity,在使用您的代码配置身份选项后,我可以获得用户 ID。结果如下:
Why User.FindFirstValue(claimtypes.nameidentifier) always return null?
对于这个问题,可能是由以下原因引起的:
当您请求 API 端点时,请求不包含具有名称标识符声明的 JWT token 或 cookie。请求API端点时,您需要添加JWT token 或cookie。
在这种情况下,您可以使用F12开发者网络工具检查请求头是否有cookie或Authorization头,引用这个截图(它使用cookie来存储身份信息):
JWT token 或 Cookie 不包含名称标识符声明。
您可以设置断点来检查用户声明,无论是否可以找到名称标识符声明。在此屏幕截图中,我使用 Asp.net core Identity,只需添加以下代码:
services.Configure<IdentityOptions>(options => options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
如果用户的声明不包含名称标识符声明,则问题可能与代码的登录部分有关,最好共享相关代码。
检查
app.UseAuthentication()
和app.UseAuthorization()
中间件,请确保已将它们正确添加到 Program.cs 或 Startup.cs 中。代码如下:
如果上述方法仍然不起作用,请分享详细步骤和代码,或者您可以创建一个最小的完整示例来重现问题。
关于asp.net-core - 为什么 User.FindFirstValue(claimtypes.nameidentifier) 总是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74265653/