ASP.NET MVC: Opposite of [Authorise]

你离开我真会死。 提交于 2019-11-30 20:39:54

I tried creating my own AuthorizationAttribute after twk's suggestion:

public class Restrict : AuthorizeAttribute
{
    private readonly string _role;

    public Restrict(string role)
    {
        _role = role;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        if (httpContext.User.IsInRole(_role))
            return false;

        return true;
    }
}

And I use it like this:

[Restrict("Administrator")]
public class HomeController : Controller
{
    // code
}

I'm unsure whether it is correct practice but it does the job.

twk

You should prepare your own ActionFilter which can implement such a feature. By default there is a rule of deny everything, but allow defined by Authorize action filter (as you already know).

Some inspiration can be found there

Dzik

Based on ajbeaven's answer, I managed to extend it to list of Roles instead of one role.

Firstly the Restrict class:

public class Restrict : AuthorizeAttribute {
    private List<string> _roles;
    public string Roles {
        get {
            string roles = "";
            if (_roles != null && _roles.Count > 0) {
                int counter = 0;
                foreach (string role in _roles) {
                    counter++;
                    if (counter == _roles.Count) {
                        roles = role;
                    } else {
                        roles += role + ",";
                    }
                }
            }
            return roles;
        }
        set {
            _roles = new List<string>();
            string[] roles = value.Split(',');
            foreach (string role in roles) {
                _roles.Add(role);
            }
        }
    }

    public Restrict() {
        _roles = new List<string>();
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        bool result = true;
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        }
        foreach (string role in _roles) {
            if (httpContext.User.IsInRole(role)) {
                result = false;
                break;
            }
        }
        return result;
    }
}

Then add the AppRoles class to make the whole solution reusable:

public static class AppRoles {
    public const string Role1 = "Role1";
    public const string Role2 = "Role2";
}

Usage:

[Authorize]
[Restrict(Roles = AppRoles.Role1 + "," + AppRoles.Role2)]
    public ActionResult Index() {
    return View();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!