【问题标题】:ClaimTypes.NameIdentifier returns email address not IdClaimTypes.NameIdentifier 返回电子邮件地址而不是 Id
【发布时间】:2017-09-10 19:27:38
【问题描述】:

我在我的 Web API 项目中使用HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value 来获取请求用户,用于身份验证。 NameIdentifier 返回当前用户的电子邮件,而 Google 搜索表明它应该返回用户的 Id(在这种情况下是 Guid,如果这很重要)。
为什么会发生这种情况,如何在没有数据库查询的情况下返回当前用户的 ID?

【问题讨论】:

  • 应用使用什么认证机制?是什么创建了 ClaimsPrincipal?是 .NET Core 2.0 吗?
  • 是的,它是 .NET Core 2.0。我正在使用 JwtBearer 进行身份验证。我不熟悉 ClaimsPrinciple,所以我认为 JwtBearer 正在处理这个问题?
  • 对不起,我的意思是身份验证(使用 JwtBeaer 作为 jwt 令牌)
  • 您找到这个问题的答案了吗?编辑:几秒钟后找到它,我为此添加答案

标签: .net-core httpcontext


【解决方案1】:

所以我搜索了一下,因为我遇到了同样的问题,根据 Auth0.com 论坛上的this reply,.NET 中的 JWT 身份验证处理程序将出于某种原因将sub 声明映射到NameIdentifier 声明类型。

所以解决方法是不设置sub声明类型,或者设置为id。

【讨论】:

  • 我无法亲自确认这是否有效,但我会将其标记为已接受的答案,因为这是一个非常古老且不活跃的问题;)
【解决方案2】:

我在使用 ASP.net core 2.0 时遇到了同样的问题,因为我生成了这样的 jwt 令牌

public ClaimsIdentity GenerateClaimsIdentity(string email, string id)
{
    return new ClaimsIdentity(new GenericIdentity(email, "Token"), new[]
    {
        new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id),
        new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol, Helpers.Constants.Strings.JwtClaims.ApiAccess)
    });
}

我尝试通过UserManager 获取CurrentUser,但它总是返回null。我想在这样的启动文件中将UserIdClaimType 字符串更改为“id”

var builder = services.AddIdentity<User,IdentityRole>(o =>
{
    // configure identity options
    o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;

    //this line
    o.ClaimsIdentity.UserIdClaimType = "id";
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多