简体   繁体   中英

How to get the name of the role from the Controller to the Custom AuthorizeAttribute class?

I am developing MVC application and using ASP.NET identity for User Roles. I have override 3 functions of AuthorizeAttribute class as:

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private ApplicationDbContext context = new ApplicationDbContext();
        private readonly string[] allowedroles;        
        public CustomAuthorizeAttribute(params string[] roles)
        { this.allowedroles = roles; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string usr = httpContext.User.Identity.Name;
            var userId = context.Users.Where(item => item.UserName == usr).Single().Id;
            var uroles = context.Roles.ToList();
            bool authorize = false;
            foreach (var role in uroles)
            {
                var user = context.Users.Where(u => u.Roles.Any(r => r.RoleId == role.Id)).ToList();
                if (user.Count() > 0)
                { authorize = true; }
            }
            return authorize;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        { filterContext.Result = new HttpUnauthorizedResult("Access is Denied!"); }
    }

Now my controller Authorization is as:

[CustomAuthorize(Roles="Delete COA")]

And my code authorize the current user for it even then when in the dbo.AspNetRoles tables I have no role assigned to the current user with the name "Delete COA". But since my CustomeAuthorizeAttribute Class is not getting the name of the role attribute from the controller I am unable to filter as per the roles of the current User.

Instead the constructor code

this.allowedroles = roles;

gets the string as:

roles = {string[0]}

but I need the name of the role here. What is wrong here?

It seems you are using property as a parameter. Since AuthorizeAttribute already have had Role property you could simply use it.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    private ApplicationDbContext context = new ApplicationDbContext(); 

    // you don't need the constrictor and private roles field  

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // spiting different roles by ',' 
        var roles=this.Rols.Split(',');
        // rest of your code
    }
}

And you could apply to any action then:

[CustomAuthorize(Roles="Delete COA")]
public ActionResoult MyFancyAction(){}

Or for multiple role you could:

[CustomAuthorize(Roles="FirstRole,SecondRole,AndSoOn")]
public ActionResoult MyFancyAction(){} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM