1

In our project management application, we need to keep access rights (per project for each user) in a separate table in db. IE.

User A can create tasks in Project #1, User A can only read task in Project #2

To succeed that, we extend our AspNetUserRoles table by adding a new coloumn(projectID).

By default, in razor view, we can check user roles with User.IsInRole("CanCreateTask"). We need to extend this method and want to check the user role for specific project Ie. User.IsInRole("CanCreateTask", project.Id)

EDITED: Also i need to check user access in controller with project.Id

[Authorize(Roles = "CanCreateTask")]

Did some research on net but could not find any solution.

umki
  • 759
  • 12
  • 31
  • Have a look at [this answer](http://stackoverflow.com/questions/31846452/claim-based-authorization-design-for-conditional-edit-operation-in-asp-net-mvc-a/31851128#31851128) – Sam FarajpourGhamari Jan 28 '16 at 09:36
  • @SamFarajpourGhamari , I read the answer and make some research. I understand that, i can write custom AuthorizeAttribute to do what i want. But on a another [SO answer,](http://stackoverflow.com/questions/31464359/custom-authorizeattribute-in-asp-net-5-mvc-6) says "We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead you should be writing authorization requirements." . I realy lost in Identity.. What is the best way – umki Feb 09 '16 at 22:10
  • The answer is great and I totally agree with it. But keep in mind the answer based on Identity v3 and ASP.Net Core (v5) so unfortunately mentioned approach, the authorization requirement, is not implemented in Identity 2. Therefore I think for current version of Identity as far as you **extend** current authorize attribute instead of writing your own authorize attribute **from scratch** it is fine. – Sam FarajpourGhamari Feb 10 '16 at 19:06

1 Answers1

4

You could create an extension method, extending the User class.

public static bool IsInRole(this User user, string role, int projectID)
{
    var isInRole = user.IsInRole(role);
    var hasRoleInProject = // Logic for deciding if it is in the role for this project

    return isInRole && hasRoleInProject; 

}

This method would be called like this:

user.IsInRole("CanCreateTask", project.Id);
Matt Hensley
  • 831
  • 8
  • 18
  • Thanks!, I edited my question. I also need to check role,project check in controller. – umki Jan 26 '16 at 19:53
  • 1
    Where should i extend the IsInRole method @Matt-Hensley ? – umki Feb 14 '16 at 11:53
  • The link in my answer outlines where and how to create extension methods. You can just create a static class to house your extension methods. – Matt Hensley Feb 14 '16 at 19:30