Accessing JWT claims in ASP.NET Core Web API

Viewed 66

My app consists of a Blazor WebAssembly SPA and an ASP.NET Core Web API. For the API I also use the repository pattern. Here's how UsersController.cs looks like:

namespace MyApp.Controllers
{
    [Authorize]
    [Route("[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private IUserRepository userRepository;

        public UsersController(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }

        [HttpGet]
        public async Task<IActionResult> GetUsers([FromBody] SearchSortFilter Options)
        {
            try
            {
                var users = await userRepository.GetUsers(Options);
                return Ok(users);
            } 
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }
}

While authentication and authorization with Azure AD B2C work very well, I need to access claims data from the JWT token as in the request header.

What is the best way I can do this? Do I just use Request.Authorization, then slice the string to leave out the Bearer part, before using JwtSecurityTokenHandler() to decode into claims?

I was wondering if there was anything like User.Indentity.Name that would allow me to access claims in an opinionated way rather than having to manually do string slicing and decode it.

0 Answers
Related