简体   繁体   中英

What is the right way to retrieve the email from the JWT token

I am working on .net 6 web api project.

In the endpoint I am retrieving the email value from the JWT token that is passed via the header.

Following code allows me to retrieve the email from the JWT token:

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. So I want to ask whether .FindFirst is the right way to do this? Or whether I should use keyword like .FirstOrDefault or .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(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM