asp.net-core - 为什么 User.FindFirstValue(claimtypes.nameidentifier) 总是返回 null?

标签 asp.net-core asp.net-core-webapi .net-6.0

我有一个 .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。结果如下:

enter image description here

Why User.FindFirstValue(claimtypes.nameidentifier) always return null?

对于这个问题,可能是由以下原因引起的:

  1. 当您请求 API 端点时,请求不包含具有名称标识符声明的 JWT token 或 cookie。请求API端点时,您需要添加JWT token 或cookie。

    在这种情况下,您可以使用F12开发者网络工具检查请求头是否有cookie或Authorization头,引用这个截图(它使用cookie来存储身份信息):

    enter image description here

  2. JWT token 或 Cookie 不包含名称标识符声明。

    您可以设置断点来检查用户声明,无论是否可以找到名称标识符声明。在此屏幕截图中,我使用 Asp.net core Identity,只需添加以下代码:services.Configure<IdentityOptions>(options => options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);

    enter image description here

    如果用户的声明不包含名称标识符声明,则问题可能与代码的登录部分有关,最好共享相关代码。

  3. 检查app.UseAuthentication()app.UseAuthorization()中间件,请确保已将它们正确添加到 Program.cs 或 Startup.cs 中。代码如下:

    enter image description here

如果上述方法仍然不起作用,请分享详细步骤和代码,或者您可以创建一个最小的完整示例来重现问题。

关于asp.net-core - 为什么 User.FindFirstValue(claimtypes.nameidentifier) 总是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74265653/

相关文章:

c# - 在 .NET Core 中解析 Timex 表达式

c# - 路由不适用于自托管 Web API

c# - 使用构造函数 Swagger 设置属性

c# - Azure函数.net 6在部署后返回错误500

ios - 如何在Azure DevOps中安装net6的iOS工作负载?

c# - VB.NET 与 C# 在控制台应用程序结束后没有显式释放任何内容而退出 Excel 有何不同?

c# - Azure Redis 缓存和 Azure CDN 之间的区别

c# - 如何手动添加到 swagger 的 schemas 部分?

c# - 获取 Azure 静态 Web 应用中托管的应用的 "proper"和 "permanent"URL

asp.net-mvc - 将对象列表绑定(bind)到表单