简体   繁体   中英

How to add 'pass parameter' to custom AuthorizeAttribute

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()

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);
    }
}

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