4

Is it somehow possible to get asp.net identity to require membership of 2 roles before granting access?

I have 2 layers of rights in my system. First a company type that grants access to certain features, and secondly one that restricts the specific method and usage rights.

CompanyType= Host,Expert,Manufacturer,Supplier,Consultant
Accesslevel= Admin,ReadOnly,ReadWrite

i want to be able to do something like this:

[Authorize(Roles = "Expert && ReadWrite || ReadOnly")]

The goal is to have one way of handling both instead of having these roles:

HostAdmin, HostReadOnly, HostReadWrite, ExpertAdmin ....

Thanks for your time.

2 Answers 2

8

Yes you can require more than one role, you just add more authorize attributes:

[Authorize(Roles="members")]
[Authorize(Roles="admin")]

This will require the user to both have the members and admin role

For more details -> Allow multiple roles to access controller action

5
  • Thank you! - Perfect answer. I struggled to find this anywhere. Mar 28, 2014 at 9:53
  • I think even comma separated works: [Authorize(Roles="members,admin")] I have used it Mar 28, 2014 at 11:30
  • 1
    hmm from what i see its not the same. The above is the same as an AND statement where VishalVaishya's example is an OR statement. Or am i wrong? Mar 28, 2014 at 12:17
  • @Wraithbone I was to quick to agree =) You're right, VishalVaishya's answer is OR, while the suggested solution is AND
    – Zaphod
    Mar 28, 2014 at 12:44
  • 2
    @VishalVaishya This will also work, but behavior is different. My suggestion is AND while your solution is OR
    – Zaphod
    Mar 28, 2014 at 12:45
5

I create a Custom filter attribute to answer your need. I made a little simplification: I change && to & and || to |. The parser also supports xor ^, not ! and parentheses

[CustomAuthorize(Roles = "Expert & (ReadWrite | ReadOnly)")]

Here is the custom authorize attribute

/// <summary>
/// [CustomAuthorize(Roles = "A & (!B | C) ^ D")]
/// </summary>
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    /*
     *  Exp -> SubExp '&' SubExp // AND
     *  Exp -> SubExp '|' SubExp // OR
     *  Exp -> SubExp '^' SubExp // XOR
     *  SubExp -> '(' Exp ')'
     *  SubExp -> '!' Exp        // NOT
     *  SubExp -> RoleName
     *  RoleName -> [a-z]
     */

    private const char TokenSeparator = ' ';
    private const char TokenAnd = '&';
    private const char TokenOr = '|';
    private const char TokenXor = '^';
    private const char TokenNot = '!';
    private const char TokenParentheseOpen = '(';
    private const char TokenParentheseClose = ')';

    abstract class Node
    {
        public abstract bool Eval(IPrincipal principal);
    }

    abstract class UnaryNode : Node
    {
        private readonly Node _expression;

        public Node Expression
        {
            get { return _expression; }
        }

        protected UnaryNode(Node expression)
        {
            _expression = expression;
        }
    }

    abstract class BinaryNode : Node
    {
        private readonly Node _leftExpression;
        private readonly Node _rightExpression;

        public Node LeftExpression
        {
            get { return _leftExpression; }
        }

        public Node RightExpression
        {
            get { return _rightExpression; }
        }

        protected BinaryNode(Node leftExpression, Node rightExpression)
        {
            _leftExpression = leftExpression;
            _rightExpression = rightExpression;
        }
    }

    class AndNode : BinaryNode
    {
        public AndNode(Node leftExpression, Node rightExpression)
            : base(leftExpression, rightExpression)
        {
        }

        public override bool Eval(IPrincipal principal)
        {
            return LeftExpression.Eval(principal) && RightExpression.Eval(principal);
        }
    }

    class OrNode : BinaryNode
    {
        public OrNode(Node leftExpression, Node rightExpression)
            : base(leftExpression, rightExpression)
        {
        }

        public override bool Eval(IPrincipal principal)
        {
            return LeftExpression.Eval(principal) || RightExpression.Eval(principal);
        }
    }

    class XorNode : BinaryNode
    {
        public XorNode(Node leftExpression, Node rightExpression)
            : base(leftExpression, rightExpression)
        {
        }

        public override bool Eval(IPrincipal principal)
        {
            return LeftExpression.Eval(principal) ^ RightExpression.Eval(principal);
        }
    }

    class NotNode : UnaryNode
    {
        public NotNode(Node expression)
            : base(expression)
        {
        }

        public override bool Eval(IPrincipal principal)
        {
            return !Expression.Eval(principal);
        }
    }

    class RoleNode : Node
    {
        private readonly string _roleName;

        public string RoleName
        {
            get { return _roleName; }
        }

        public RoleNode(string roleName)
        {
            _roleName = roleName;
        }

        public override bool Eval(IPrincipal principal)
        {
            return principal.IsInRole(RoleName);
        }
    }

    private Node _expression;

    void Parse(string text)
    {
        if (text == null) throw new ArgumentNullException("text");

        var delimiters = new[] { TokenSeparator, TokenAnd, TokenOr, TokenXor, TokenNot, TokenParentheseOpen, TokenParentheseClose };

        List<string> tokens = new List<string>();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < text.Length; i++)
        {
            char c = text[i];
            if (c == TokenSeparator)
                continue;

            if (delimiters.Contains(c))
            {
                if (sb.Length > 0)
                {
                    tokens.Add(sb.ToString());
                    sb.Clear();
                }

                tokens.Add(c.ToString(CultureInfo.InvariantCulture));
            }
            else
            {
                sb.Append(c);
            }
        }

        if (sb.Length > 0)
        {
            tokens.Add(sb.ToString());
        }

        _expression = Parse(tokens.ToArray());
    }

    Node Parse(string[] tokens)
    {
        int index = 0;
        return ParseExp(tokens, ref index);
    }

    Node ParseExp(string[] tokens, ref int index)
    {
        Node leftExp = ParseSubExp(tokens, ref index);
        if (index > tokens.Length)
            return leftExp;

        string token = tokens[index];

        if (token == "&")
        {
            index++;
            Node rightExp = ParseSubExp(tokens, ref index);
            return new AndNode(leftExp, rightExp);
        }
        else if (token == "|")
        {
            index++;
            Node rightExp = ParseSubExp(tokens, ref index);
            return new OrNode(leftExp, rightExp);
        }
        else if (token == "^")
        {
            index++;
            Node rightExp = ParseSubExp(tokens, ref index);
            return new XorNode(leftExp, rightExp);
        }
        else
        {
            throw new Exception("Expected '&' or '|' or EOF");
        }
    }

    Node ParseSubExp(string[] tokens, ref  int index)
    {
        string token = tokens[index];

        if (token == "(")
        {
            index++;
            Node node = ParseExp(tokens, ref index);

            if (tokens[index] != ")")
                throw new Exception("Expected ')'");

            index++; // Skip ')'

            return node;
        }
        else if (token == "!")
        {
            index++;
            Node node = ParseExp(tokens, ref index);
            return new NotNode(node);
        }
        else
        {
            index++;
            return new RoleNode(token);
        }
    }

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

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        if (_expression == null)
        {
            Parse(Roles);
        }

        if (_expression != null)
        {
            return _expression.Eval(user);
        }

        return true;
    }
}

Otherwise you can use the default AuthorizeAttribute

// (role1 OR role2) AND (role3 OR role4)
[Authorize(Roles = "Role1, Role2")] 
[Authorize(Roles = "Role3, Role4")] 
1
  • Love the Custom filter idea. I will take a look at this as i can use it for another problem i have. Thank you for the extensive explanation. For this particular question i used Zaphods answer that you also explained at the bottom. Mar 29, 2014 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.