Search code examples
c#asp.netasp.net-mvc-4asp.net-authorization

Customized authorization attribute in MVC 4 with Roles


I have created a customized role base authorization attribute.My idea is that when a user with role name "employee" Log In should not be allowed to access the "admin" page through URL. But when I implement the [MyRoleAuthorization] in Employee controller and Log In the error says "This webpage has a redirect loop". This is code for [MyRoleAuthorization]

public class MyRoleAuthorization : AuthorizeAttribute
{
    string isAuthorized;
    private string AuthorizeUser(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext != null)
        {
            var context = filterContext.RequestContext.HttpContext;


            if (Convert.ToString(context.Session["RoleName"]) == "Admin")
            {
                isAuthorized = "Admin";

            }
            else if (Convert.ToString(context.Session["RoleName"]) == "Employee")
            {
                isAuthorized = "Employee";

            }
            else if (Convert.ToString((context.Session["RoleName"])) == "Customer")
            {
                isAuthorized = "Customer";
            }
            else
            {
                throw new ArgumentException("filterContext");
            }
        }
        return isAuthorized;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentException("filterContext");

        if (AuthorizeUser(filterContext) == "Admin")
        {
            filterContext.Result = new RedirectToRouteResult
                 (new RouteValueDictionary(new { controller = "Admin" }));
        }

        else if (AuthorizeUser(filterContext) == "Employee")
        {
            filterContext.Result = new RedirectToRouteResult
                 (new RouteValueDictionary(new { controller = "Employee" }));
        }
        else if (AuthorizeUser(filterContext) == "Customer")
        {
            filterContext.Result = new RedirectToRouteResult
                 (new RouteValueDictionary(new { controller = "Customer" }));

        }
    }

}
} 

My Employee controller looks like this

   [MyRoleAuthorization]        
    public ActionResult Index()
    {
        var employee = db.Employee.Include(e => e.User);
        return View(employee.ToList());
    }

Can you please help me.


Solution

  • Your redirection code is always going to redirect the user to the Employee Index Action, even when the action your are redirecting to is authenticated for the employee. You will need to provide another set of rules in your authorization and change your OnAuthorize method.

    Such as

    public class MyRoleAuthorization : AuthorizeAttribute
    {
    /// <summary>
    /// the allowed types
    /// </summary>
    readonly string[] allowedTypes;
    
    /// <summary>
    /// Default constructor with the allowed user types
    /// </summary>
    /// <param name="allowedTypes"></param>
    public MyRoleAuthorization(params string[] allowedTypes)
    {
        this.allowedTypes = allowedTypes;
    }
    
    /// <summary>
    /// Gets the allowed types
    /// </summary>
    public string[] AllowedTypes
    {
        get { return this.allowedTypes; }
    }
    
    /// <summary>
    /// Gets the authorize user
    /// </summary>
    /// <param name="filterContext">the context</param>
    /// <returns></returns>
    private string AuthorizeUser(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext != null)
        {
            var context = filterContext.RequestContext.HttpContext;
            string roleName = Convert.ToString(context.Session["RoleName"]);
            switch (roleName)
            {
                case "Admin":
                case "Employee":
                case "Customer":
                    return roleName;
                default:
                    throw new ArgumentException("filterContext");
            }
        }
        throw new ArgumentException("filterContext");
    }
    
    /// <summary>
    /// The authorization override
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentException("filterContext");
        string authUser = AuthorizeUser(filterContext);
        if (!this.AllowedTypes.Any(x => x.Equals(authUser, StringComparison.CurrentCultureIgnoreCase)))
        {
            filterContext.Result = new HttpUnauthorizedResult();
            return;
        }
    }
    

    }

    This can then be decorated as

    public class EmployeeController : Controller
    {
        [MyRoleAuthorization("Employee")]
        public ActionResult Index()
        {
            return View();
        }
    }
    

    Now your login code should be modified to send the user to the correct controller.