简体   繁体   English

从 JWT 令牌中检索 email 的正确方法是什么

[英]What is the right way to retrieve the email from the JWT token

I am working on .net 6 web api project.我正在研究 .net 6 web api 项目。

In the endpoint I am retrieving the email value from the JWT token that is passed via the header.在端点中,我从通过 header 传递的 JWT 令牌中检索 email 值。

Following code allows me to retrieve the email from the JWT token:以下代码允许我从 JWT 令牌中检索 email:

string email = HttpContext.User.FindFirst(ClaimTypes.Email)?.Value

I know that FindFirst is meant to be used when I am expecting multiple values and I want to retrieve the first.我知道 FindFirst 是在我期望多个值并且我想检索第一个值时使用的。 So I want to ask whether .FindFirst is the right way to do this?所以我想问一下.FindFirst是否是正确的方法? Or whether I should use keyword like .FirstOrDefault or .Single ?或者我是否应该使用.FirstOrDefault.Single之类的关键字?

I would suggest making an extension method:我建议制作一个扩展方法:

 public static string GetUserEmail(this HttpContext httpContext)
 {
      if (httpContext.User == null)
      {
          return string.Empty;
      }

      return httpContext.User.Claims.Single(x => x.Type == ClaimTypes.Email).Value;
  }

Make sure you add the following Authorize attribute to your controller where you will call the extension method from, and that you add the email claim when creating the JWT token.确保将以下 Authorize 属性添加到您将从中调用扩展方法的 controller 中,并确保在创建 JWT 令牌时添加 email 声明。

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 SignalR 请求中检索承载 jwt 令牌 - Retrieve bearer jwt token from SignalR request 验证 JWT 令牌签名的最简单方法是什么? - What is the easiest way to validate the signature of a JWT token? 提交后,无需重新显示显示卡即可从Adaptive Card检索数据的正确方法是什么? - What is the right way to retrieve data from Adaptive Card without displayed card again after submit? 使用Entity Framework 6检索数据的正确有效方法是什么 - What is the right and efficient way to retrieve data using Entity Framework 6 没有从身份服务器获取用户“电子邮件”作为索赔(来自jwt令牌) - Not getting user “email” as a claim (from jwt token) back from identity server 在.NET中命名电子邮件附件的正确方法是什么? - What's the right way to name an email attachment in .NET? 如何从外部API读取jwt令牌以验证用户并在数据库中插入用户名和电子邮件ID - How to read jwt token from external API to authenticate user and insert the user name and email id in the database 从ClaimsIdentity检索WindowsIdentity的最佳方法是什么 - What is the best way to retrieve a WindowsIdentity from a ClaimsIdentity 从数据库填充DropDownList的正确方法是什么? - What is the right way to populate a DropDownList from a database? 从 MainPage 调用任务的正确方法是什么 - What is the right way to call a Task from MainPage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM