In my project I have implemented ASP.NET Identity 2.x with claims based authorization plus authentication. I have added added support for a claims authorization attribute as described here.
Here are the claims I'va come up with that would allow/disallow CRUD on employees.
public class ResourceClaimTypes
{
public const string CreateEmployee = "urn:company:Employee:Create";
public const string ReadEmployee = "urn:company:Employee:Read";
public const string UpdateEmployee = "urn:company:Employee:Update";
public const string DeleteEmployee = "urn:company:Employee:Delete";
}
An action would look like this:
[ClaimsAuthorize( ResourceClaimTypes.ReadEmployee )]
public ActionResult Index()
{
return View();
}
What I don't quite understand is how to make use of those claims in a view and its view model. For instance, there is a view for displaying employees, which is a simple grid. Then there are views for editing and creating employees.
What the view and view model should be capable of doing now is hiding or showing the Save/Update/Delete buttons according to the user's claims.
Approach on the views:
Index -> should display all employees if ReadEmployee claim is present, otherwise the view should still be accessible, but with a message "No premission to view employees".
Create/Edit -> the user should still be able to nvaigate to these views, but the "Create"/"Save" buttons should not be visible.
Delete -> all "Delete" buttons should be hidden.
Bottom line is, views should be accessible, but the Create/Save buttons should be hidden.
How can that be done?
* UPDATE / MY SOLUTION *
This is how I ended up doing it. Following Derek's suggestion I have used Action/Resource based authentication. Along with ASP.NET Identity I have implemented the IUserClaimStore interface to grab the claims from the DB.
The Views and ViewModels (!) do NOT contain ANYTHING like CanRead, CanWrite! I am using KendoUI and have created an extension method for buttons.
Inside the extension method I can access the custom ResourceAuthorizationManager (see blog from Dominik Baier). So when creating the button, I can call HttpContaxtBase.CheckAccess(...) to determine if the button should be enabled/visible, or not.
The only thing I need is a way to tell the extension method what action/resource combination to check access for.
Razor Example:
@Html.LinkButton(Action.Create, Resource.Employee)
This is all that is needed in the view to display (or not) a button that says "Create" and points to the Create view of the Employee controller. Very clean, IMHO.
You should look at a product of Dominic Baier at Thinktecture for something like this.
The following article will explain how to achieve what your looking for quite elegantly.
They have example in there Git Hub repo.
** EDIT **
Here is the link to the GitHub Example you need to follow.