MVC 3 Authorize custom roles

半城伤御伤魂 提交于 2019-12-05 20:42:18

Your Role.IsInRole usage isn't correct. Thats what the [Authorize(Roles="Admin")] is used for, no need to call it.

In your code you are not setting the roles anywhere. If you want to do custom role management you can use your own role provider or store them in the auth token as shown here:

http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization note the section:


// Get the stored user-data, in this case, user roles
            if (!string.IsNullOrEmpty(ticket.UserData))
            {
                string userData = ticket.UserData;
                string[] roles = userData.Split(',');
                //Roles were put in the UserData property in the authentication ticket
                //while creating it
                HttpContext.Current.User = 
                  new System.Security.Principal.GenericPrincipal(id, roles);
            }
        }


However an easier approach here is to use the built in membership in asp.net. Create a new mvc project using the 'internet application' template and this will all be setup for you. In visual studio click on the "asp.net configuration" icon above solution explorer. You can manage roles here and assignment to roles.

I know this question is a bit old but here's how I did something similar. I created a custom authorization attribute that I used to check if a user had the correct security access:

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        // Get the roles from the Controller action decorated with the attribute e.g.
        // [AccessDeniedAuthorize(Roles = MyRoleEnum.UserRole + "," + MyRoleEnum.ReadOnlyRole)]
        var requiredRoles = Roles.Split(Convert.ToChar(","));

        // Get the highest role a user has, from role provider, db lookup, etc.
        // (This depends on your requirements - you could also get all roles for a user and check if they have the correct access)
        var highestUserRole = GetHighestUserSecurityRole();

        // If running locally bypass the check
        if (filterContext.HttpContext.Request.IsLocal) return;

        if (!requiredRoles.Any(highestUserRole.Contains))
        {
            // Redirect to access denied view
            filterContext.Result = new ViewResult { ViewName = "AccessDenied" };
        }
    }
}

Now decorate the Controller with the custom attribute (you can also decorate individual Controller actions):

[AccessDeniedAuthorize(Roles="user")]
public class ProductController : Controller
{
    [AccessDeniedAuthorize(Roles="admin")]
    public ViewResult Index()
    {
        var product = db.Product.Include(a => a.Category);
        return View(product.ToList());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!