Search code examples
c#asp.net-mvcbitwise-or

Bitwise OR as a input parameter in custom attribute


How to pass multiple parameters with bitwise OR operation in my custom FeatureAuthorize attribute, same way AttributeUsage supports AttributeTarget as a method or class.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]

Below are the example that I want to achieve, any of the feature provided either send money or receive money method should be accessible.

[FeatureAuthorize(Feature = EnumFeature.SendMoney | EnumFeature.ReceiveMoney)]
public ActionResult SendOrReceiveMoney(int? id, EnumBankAccountType? type)
{
 // My code
}

Body of the FeatureAuthorize Attribute is like.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class FeatureAuthorizeAttribute : AuthorizeAttribute
{
    public EnumFeature Feature { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!IsFeatureAllowed(Feature)) // Verification in database.
        {
             // Redirection to not authorize page.
        }
    }
}

Thanks in advance.


Solution

  • Define your EnumFeature like this:

    [Flags]
    public enum EnumFeature {
      Send = 1,
      Received = 2,
      BalanceEnquery = 4,
      CloseAccount = 8
    }
    

    Notice how each subsequent enum value is the next highest power of 2. In your auth attribute, you can use Enum.HasFlag to see if a flag is set. But you'll probably want to ensure that other flags aren't set by using other bitwise operations.

    Something like this

    var acceptable = EnumFeature.Send | EnumFeature.Received;
    var input = EnumFeature.Send | EnumFeature. CloseAccount;
    
    // Negate the values which are acceptable, then we'll AND with the input; if that result is 0, then we didn't get any invalid flags set.  We can then use HasFlag to see if we got Send or Received
    var clearAcceptable = ~acceptable;
    Console.WriteLine($"Input valid: {(input & clearAcceptable) == 0}");