Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Authentication - Hide Element in View based on roles

Is there a possibility to hand over the Result of the Authorize-Attribute to the View?

Let's assume I want to hide 5 links in my Index view based on the memberships of a User.

[Authorize(Roles = "Admin")]
public ActionResult Index(){
    ....
}

The code above will prevent all users that are not part of the Admin-Group from visiting the Index page.

@{
    if(User.IsInRole("Admin"){
        <a href="#">Some link to be hidden</a>
    }
}

This code will hide the link if the User is not part of the Admin role. This is basically what I want BUT using this method I have to change the role name on every hidden link if the role would change.

Isn't there something like a combination of both? (Schema see below)

[Authorize(Roles = "Admin")] //This will pass true to the View if the User is a member of the group "Admin"
public ActionResult Index(){
    ....
}

@{
    if(User.IsAuthenticated){ //This will read the "Token" and if it's true the if statement will get executed.
        <a href="#">Some link to be hidden</a>
    }
}

So - if the User is in Role "Admin" the link will be shown. Is this possible?

like image 426
Th1sD0t Avatar asked Oct 19 '16 17:10

Th1sD0t


1 Answers

You could use ViewBag and ViewData among other things, but I'd suggest passing a model back to the view with properties indicating whether to display the links or not.

public class YourViewModel()
{
    public bool ShowHiddenLinks { get; set; }
    // ... whatever other properties
}

In your controller you'd then do:

[Authorize(Roles = "Admin")] 
public ActionResult Index()
{
    var yourVm = new YourViewModel();
    yourVm.ShowHiddenLinks = true;

    return View(yourVm);
}

And your view becomes:

@model YourViewModel

/* ShowHiddenLinks is true & this view is meant for admins only,
   so show admin-related links */
@if (Model.ShowHiddenLinks)
{
    <a href="#">Some link to be hidden</a>
}

I've named the viewmodel property ShowHiddenLinks on purpose, so that it becomes re-usable for views meant for other users as well. You can of course extend the viewmodel to feature properties for other roles (e.g. a view which is accessible by admins and moderators, each with their own distinct set of hidden links), or create one viewmodel per role—it all depends on the scenario.

like image 120
trashr0x Avatar answered Oct 11 '22 08:10

trashr0x