0

I have a site with links throughout it for performing actions. Some need to be hidden if the user is not in the admin role. I am doing checking on the backend just in case someone types i n the url directly etc. but is it enough to have this in the razor view?

<ul>
<li>Home</li>
<li>Items</li>
@if(User.IsInRole("Admin"){
    <li>Users</li>
}
</ul>
the-a-train
  • 1,123
  • 13
  • 32

2 Answers2

5

Yep, that is sufficient.

Or as I found in another post which i used lately:

public static MvcHtmlString If(this MvcHtmlString value, bool evaluation)
{
     return evaluation ? value : MvcHtmlString.Empty;
}

so you can use this:

@Html.ActionLink("Create New", "Create").If(User.IsInRole("Admin"))

However, if you are using links to other pages which you need to prevent from accessing when not in a specific role. You should also include the Authorize attribute in the controllers you want to prevent them from accessing:

public class HomeController : Controller
{
    [Authorize(Roles="Admin")]
    public ActionResult Index()
    { 
        return View();
    }
} 
Rody
  • 2,675
  • 1
  • 22
  • 40
0

Yes. Also add attribute to respective method in your controller to prevent manual calls

[Authorize( Roles = "Admin" )]
Cheburek
  • 2,103
  • 21
  • 32