Application authentication
.NET Core ASP.NET Core Identity C# JWT Razor Visual Studio

Retrieving Roles from JWT Token Claims in a .NET Core Application

Welcome to today’s post.

In a previous post I showed how to embed user roles into a JWT token.

In this post I will be showing how to retrieve user roles from JWT token using .NET Core.

The most common use of roles is to implement authorization within applications or web API services.

In another previous post I showed how to obtain and persist a JWT token into a web application or web API cookie. Below is our method that is used to determine if the application’s current user is a member of the given role:

public async Task<bool> IsCurrentUserInRole(string role)
{
  bool rslt = false;
  string bearerToken = _context.Request.Cookies["token"];
  ClaimsPrincipal claimsPrincipal =
    _tokenManager.GetPrincipal(bearerToken);
  foreach (Claim claim in claimsPrincipal.Claims)
  {
    if (claim.Type == ClaimTypes.Role)
    {
      if (claim.Value == role)
      {
        rslt = true;
        break;
      }
    }
  }
  return rslt;
}

The above would work if we enabled cookies as an authentication method. If we enabled token-based authentication, then the method of retrieval of our token value would be Request.Headers.HeaderAuthorization.

Further details of our token generation implementation can be seen in a previous post. If our token fails to validate the result returned will be a null.

During debugging, the ClaimsPrincipal obtained from the token manager contains a number of claims of which we can obtain values from the role claims:

The above method can be called from any methods within our application or exposed as an API method. Below we show an example of use from Razor UI cshtml:

@if (await UserRoleService.IsCurrentUserInRole("Admin"))
{
  {
    <a asp-area="" asp-controller="Book" asp-action="Delete" asp-route-id="@Html.ValueFor(model => model.BookViewModel.ID)"> | Delete Book</a>
  }
}

That’s all for today’s post.

I hope this post has been useful and informative.

Social media & sharing icons powered by UltimatelySocial