1

I've successfully implemented role and claim (policy) based authorisation in my app. I'm using ASP.NET CORE 7 MVC. The top menu navigation is hidden base on the login user's role something like this:

 @if (User.IsInRole("Admin"))
 {      
   <li class="nav-item"><a class="nav-link text-dark" asp-action="" asp- controller="">Audit</a>  
   </li> 
 }

so the above will only show if the login user has a role of Admin (doesn't matter the policy assigned). My question is I want to show/hide the nav like based on the claim/policy assigned to other users (other than an Admin, say I want to select a specific user to access the audit page)

I thought I could do something like this (but it's not working)

@if(User.HasClaim(c => c.Type == "ViewAuditPage" && c.Value == "True"))
{      
   <li class="nav-item"><a class="nav-link text-dark" asp-action="" asp- controller="">Audit</a>  
   </li> 
 }

Any idea how to show/hide nav menu base on claim/policy Authorisation?

Jeff
  • 115
  • 7
  • Hi @Jeff, how do you add the claim to User? If you use default Identity, remember to call `_signInManager.Context.SignInAsync` with updated `ClaimsIdentity` after you add the claim. Otherwise, you may not access the claim in the next request. – Rena Mar 14 '23 at 02:01
  • Hi Rena, thanks for your response, yes I used the default identity. My issue isn’t with signing out and back in to access the claim tho. I can access the claim instantly when added as I updated the program.cs to something like this: new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true } – Jeff Mar 14 '23 at 07:07

0 Answers0