How to add 'pass parameter' to custom AuthorizeAttribute

19,277

AuthorizeAttribute already has Roles property which can be used for this purpose:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);            
        if (!isAuthorized)
        {
            return false;
        }

        string username = httpContext.User.Identity.Name;

        UserRepository repo = new UserRepository();

        return repo.IsUserInRole(username, this.Roles);
    }
}
Share:
19,277
1110
Author by

1110

Updated on July 23, 2022

Comments

  • 1110
    1110 almost 2 years

    I want to secure controller action so that only users with role "Admin" can get in.
    I don't use Role/Membership provider at all everything is custom.
    I made this so far:

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);            
            if (!isAuthorized)
                return false;
    
            string username = httpContext.User.Identity.Name;
    
            UserRepository repo = new UserRepository();
    
            return repo.IsUserInRole(username, "Admin");
        }
    }
    

    Notice that I hardcoded "Admin" here.
    I want that this be dynamic.
    This work now:

    [CustomAuthorize]
            public ActionResult RestrictedArea()...
    

    But I want something like this:

    [CustomAuthorize(Roles = "Admin")]
            public ActionResult RestrictedArea()
    
  • buvi suri
    buvi suri about 8 years
    I am getting this.Roles value as null
  • Zbigniew
    Zbigniew about 8 years
    Did you pass value to Roles variable [CustomAuthorize(Roles="admin")]?
  • Zbigniew
    Zbigniew about 8 years
    Unfortunately, without your code I cannot help you. I can, however give you advice. Firstly try step-by-step debugging (including breakpoint on Roles setter, which will require provding custom set method, not the automatical which we have here) and trying to reporduce it in a new (minimal) project.
  • Dr Blowhard
    Dr Blowhard over 6 years
    AuthorizeAttribute already has a property 'Roles'. remove the public string Roles { get; set; } and leave the rest as it is