0

I am working on an ASP.NET Core 3.1 web application that connects to a web API for authentication. For a successful login, the API will send back a JWT(token) with the user roles and other pertinent information.

This code is in my Web API LoginController

        /// <summary>
        /// Login asynchronously
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<IActionResult> LoginAsync()
        {
            try
            {
                reader = new StreamReader(HttpContext.Request.Body);
                string requestFromPost = await reader.ReadToEndAsync();

                creds = JsonConvert.DeserializeObject<UserCredentials>(requestFromPost);

                var response = await authService.CreateAccessTokenAsync(creds);
                if (!response.Success)
                {
                    return BadRequest(response.Message);
                }

                var accessRscToken = new AccessTokenResource();

                accessRscToken.AccessToken = response.Token.Token;
                accessRscToken.RefreshToken = response.Token.RefreshToken.Token;
                accessRscToken.Expiration = response.Token.RefreshToken.Expiration; //expiration for refresh token
                accessRscToken.Message = "Login Successful.";
                accessRscToken.Status = HttpStatusCode.OK.ToString();
                accessRscToken.StatusCode = ((int)HttpStatusCode.OK).ToString();

                return Ok(accessRscToken);
            }
            catch (Exception ex)
            {
                //TODO: clean this up. 17/12/2020
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }

I am able to get the claims principal after reading the JWT using the following code, in my web app(client) LoginController

var handler = new JwtSecurityTokenHandler(); //create new JwtSecurityTokenHandler
var jsonToken = handler.ReadJwtToken(authToken); //read the token
var claims = jsonToken.Claims; //get the roles/claims in the token

var principal = new ClaimsPrincipal(new ClaimsIdentity(claims)); //create a ClaimsPrincipal object

I want to hide or show menus in the navigation bar based on the roles from the JWT, using the following code in the view.

@if(User.IsInrole("Administrator"))
{ 
  //show menu if user in administrator role
}

How can I access the ClaimsPrincipal object in the view, or propagate the roles to the User object.

Thanks in advance.

Onsongo Moseti
  • 419
  • 4
  • 7

0 Answers0