[英]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.