Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing rights with ASP.NET Identity

We are currently working on a smaller ASP.NET MVC 5 application using ASP.NET Identity. It allows us to maintain different projects and their tasks. We recently implemented basic authentication so we are able to register a user with our site and login with them.

We want to be able to manage access rights on project basis so we can say for every single user that he has read, write, admin or no permissions for a specified project.

My first thought was that we can create a simple new table in our database which stores the user rights. But I feel that there might be a built-in way to achieve this with ASP.NET Identity.

So my question really is, which path we should follow - manually building a new table to administer the rights or use something built-in provided by ASP.NET Identity.

like image 779
Thorakas Avatar asked Dec 22 '14 12:12

Thorakas


1 Answers

use something built-in provided by ASP.NET Identity

The only things you could use there are claims or roles and both are not built for what you want IMO.

So I would go with your own table which links the project to a user, e.g.:

public class UserProjectRights
{
    [Key]
    public ApplicationUser User { get; set; }
    [Key]
    public Project Project { get; set; }

    public AccessRight Right { get; set; }
}

Then whenever you do some actions where a specific right is required you need to check for that. There are several ways how you could do that. In my app I created "access right check extensions" like the following (I have defined a common interface for all "access right entities" to "reuse" that method):

public static bool? CanView(this ApplicationUser user, Project project)
{
     var userRight = project.Rights.FirstOrDefault(r => r.User == user);
     return userRight == null ? (bool?)null : userRight.Right.HasFlag(AccessRight.View);
}

assuming AccessRight is an enum like:

[Flags]
public enum AccessRight
{
    View,
    Edit,
    Admin
}

Then you can do something like the following in your logic:

if (user.CanView(project) == true)
{
    // show project
}

I used bool? so I can implement different "default behaviour" as I know if null is returned there is no right defined.

like image 54
Christoph Fink Avatar answered Sep 30 '22 12:09

Christoph Fink