2

I have a ASP.NET MVC4 web application with tables users, roles and rolePrivileges

userid username password roleid] values: 1 user1 12345 3, 2 user2 12345 1, 3 user3 12345 2

[roleid, rolename ] values: 1 admin, 2 client, 3 guest, 4 ...

[Roleid, Action, GrantAccess] values: 1 /Home/Index Y 1 /Home/Settings Y 1 /Home/Dashboard Y 2 /Home/Index Y 2 /Home/Settings N 2 /Home/Dashboard Y 3 /Home/Index Y 3 /Home/Settings N 3 /Home/Dashboard N

I would like to achieve the following in ASP.NET MVC forms authentication:

A controller action should be dynamically granted denied access to a role , and if a user tries to access a controller action which the user is not granted access the application should signout.

1) I want to know the best way to achieve this since hardcoding the rolename like Authorize(Roles="admin")] will not work

2) I also have user specific settings which would need to be initialized on user log in ,in asp.net forms this was stored in session variables can the same be done using TempData in asp.net MVC is this is best practice?

4

1 回答 1

3

您可以基于角色组而不是角色创建操作过滤器。角色组可以以一对多的关系存储在您的数据库中。(即 1 组有许多角色)。然后将组名称提供给操作过滤器。

public class RoleGroupFilterAttribute : ActionFilterAttribute
{
    public string GroupName { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string [] users = new string[] {};
        string [] roles = new string[] {};

        // get the roles / users for the group from your db or storage
        // below is an example only
        roles = mydb.RoleGroups.Where(r=>r.Name == GroupName).Select(r=>r.Roles).ToArray();

        var user = filterContext.HttpContext.User;
        var userRoles = Roles.GetRolesForUser();

        if (!roles.Any(r => userRoles.Contains(r)) && !users.Contains(user.Identity.Name))
        {
            // return a not found result or redirect to an action
            filterContext.Result = new HttpNotFoundResult();
        }
    }
}

要使用您可以简单地创建管理页面来管理您的角色组。并且将过滤器添加到您的控制器或操作非常容易。

[RoleGroupFilter(GroupName="MyGroup")]
public ActionResult Index()
{
    return View();
}

在上面的示例中,我还允许将用户添加到角色组,但这将是您的选择。

于 2013-07-01T03:46:27.723 回答