Alex Rivera | Logout

Security in MVC Views

Asked 2011-10-20T17:51:56.210
11

In my MVC application I have a few different roles: Admin, General User, etc., etc.

I know that I can apply security to my Controllers via the Authorize attribute:

[Authorize(Roles="Admin")]
public ActionResult Create()
{
    return View();
}

But I also need to apply some security to the Views to not display certain sections of the View to certain roles:

@if( User.IsInRole("Admin") )
{
    @Html.ActionLink("Create", "Create")
}

Is it better to do it the above way, or handle this sort of security in a ViewModel:

public ActionResult Index()
{
    var model = new IndexViewModel();

    model.CanCreate = User.IsInRole("Admin");

    return View(model);
}

View:
@( Model.CanCreate )
{
    @Html.ActionLink("Create", "Create")
}

Does the second method have any benefits compared to the first or is it just a preference thing?

Edit
Report

1 Answer

1

You may need both...

Note that the 2nd one alone would not be secure, a user might be able to construct the URL for the actionlink in the browsers addressbar. So you absolutely need the attribute for security.

The second one is more a matter of user-friendliness or UI design. Maybe you want the user to be able to click Create and then have a choice to login differently.

answered 2011-10-20T17:56:18.030

Your Answer