109221793
109221793

Reputation: 16887

Authorize Attribute Not Working with Roles MVC C#

I'm modifying a system written in c# MVC at the moment.

I've just built in an extra bit of functionality in the Administrator area that allows the administrator create a user account that has limited administrator functionality. I've put the following over each of the controllers for the new functionality:

[Authorize(Roles = "Administrator")]

However, if I log in using limited administrator account, and navigate to this page, it lets me through.

I'm stumped because I appear to be doing this the right way but I'm also fairly new to MVC, is there anything else I can check? I haven't changed anything in the web.config file so that should be ok.

I know there's limited information above, not looking for a ready-made solution, more advice on what I can check to correct the issue.

thanks

EDIT:

This is how the new role/account was created. Go easy too, this is a first ditch attempt, there's not much validation.

[Authorize(Roles = "Administrator")]
    [HttpPost]
    public ActionResult AddSalesManager(App.Web.Areas.Administrator.Models.SalesManager model, FormCollection formValues)
    {
        if (formValues["Cancel"] != null)
        {
            return RedirectToAction("Index");
        }

        if (!string.Equals(model.password, model.confirmpassword))
        {
            ModelState.AddModelError("password", "Password and Confirmation must match");
        }

        if (ModelState.IsValid)
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                // First, create the user account inside the ASP.Net membership system.
                //

                Membership.ApplicationName = "App";
                Roles.ApplicationName = "App";

                if (!Roles.RoleExists("LimitedAdmin"))
                    Roles.CreateRole("LimitedAdmin");

               // MembershipCreateStatus createStatus = MembershipService.CreateUser(model.email, model.password, model.email);
                if (Membership.GetUser(model.email) == null)
                {
                    Membership.CreateUser(model.email, model.password);
                    Roles.AddUserToRole(model.email, "LimitedAdmin");
                }

            }
        }
        return RedirectToAction("Index");

    }

Upvotes: 1

Views: 3787

Answers (2)

Rajesh Kumar
Rajesh Kumar

Reputation: 622

Role attribute

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class PermissionsAttribute : ActionFilterAttribute
{
    private readonly PermissionsType required;

    public PermissionsAttribute()
    {
    }

    public PermissionsAttribute(PermissionsType required)
    {
        this.required = required;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Log("OnActionExecuting", filterContext.RouteData);

        HttpSessionStateBase session = filterContext.HttpContext.Session;
        Controller controller = filterContext.Controller as Controller;

        //This is uesd to  redirect to same controller but differnect action
        // controller.HttpContext.Response.Redirect("./Login");

        var rjasthan = filterContext;


        var URK = filterContext.HttpContext.Request.RawUrl;
        if (session["UserPermissions"] != null)
        {
            if (!CheckPermissions((UserPermission)session["UserPermissions"]))
            {
                // this is used to signout from sesssion
                //  filterContext.HttpContext.GetOwinContext().Authentication.SignOut();

                filterContext.Controller.TempData["AuthenticationMessages"] = "You are not authorized to access";

                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{
                             { "controller", "Home" },{ "action", "UnAuthorizeAccess" }});

            }
        }

        base.OnActionExecuting(filterContext);

    }

    protected bool CheckPermissions(UserPermission model)
    {
        bool result = false;

        if (this.required == (PermissionsType.Add))
        {
            if (model.AddRight)
                result = true;
        }
        else if (this.required == (PermissionsType.View))
        {
            if (model.ViewRight)
                result = true;
        }
        else if (this.required == (PermissionsType.Edit))
        {
            if (model.EditRight)
                result = true;
        }
        else if (this.required == (PermissionsType.Delete))
        {
            if (model.DeleteRight)
                result = true;
        }
        else if (this.required == (PermissionsType.View | PermissionsType.Edit))
        {
            if (model.ViewRight && model.EditRight)
            {
                result = true;
            }
        }
        else if (this.required == (PermissionsType.Add | PermissionsType.Edit))
        {
            if (model.AddRight && model.EditRight)
            {
                result = true;
            }
        }


        return result;
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }
}

[Flags]
public enum PermissionsType
{
    View = (1 << 0),
    Add = (1 << 1),
    Edit = (1 << 2),
    Delete = (1 << 3),
    Admin = (View | Add | Edit | Delete)
}



 [Permissions(PermissionsType.Add)]
    public ActionResult Register()
    {
        return this.AjaxableView();
    }

Upvotes: 3

Mariusz
Mariusz

Reputation: 1409

What do you expect from this code?

With this attribute you gain all users in the administrator role the right to execute this controller action no matter how limited the account is.

Upvotes: 2

Related Questions