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.


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, eg:

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.

链接地址: http://www.djcxy.com/p/24104.html

上一篇: 为什么受保护的修饰符在Java子类中的行为有所不同?

下一篇: 使用ASP.NET标识实现权限