Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you completely hide an element from a user based on their ASP.NET Identity Role?

Goal: Hide certain elements like page links from users based on their role in ASP.NET Identity.

What I have tried: [Authorize(Roles = IdentityHelper.Administrator)]

(This does restrict access to certain elements if you put the annotation over them, like pages, but it doesn't hide the element itself. I want it to do both.) Its not entirely critical that I hide these elements from the user since they're already restricted, but it would make my website look better to the users.

(IdentityHelper is just a helper class that sets up all the details about the administrator role)

Code Example:

//Restricts access, which is good, but does not completely hide elements from user.
[Authorize(Roles = IdentityHelper.Administrator)] 
public  async Task <IActionResult> Edit(int id)
{
    //get pixel art with corrosponding id
    PixelArt p =  await PixelDBManager.GetSinglePixelAsync(id, _context);

    //pass pixel art to view
    return View(p);
}

Should I perhaps switch to Claims or Policy based identity instead of Roles or can I stick with Roles to solve this particular problem?

like image 669
KnightShade Avatar asked Oct 30 '25 08:10

KnightShade


1 Answers

You can use User.IsInRole() in your Razor template.

@if(User.IsInRole(IdentityHelper.Administrator))
{
    <h1>I'm an administrator</h1>
}
like image 173
Angius Avatar answered Nov 02 '25 00:11

Angius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!