Custom MVC AuthorizeAttribute that allows multiple role membership

I have my own class AuthorizeAttribute created to handle granular authorization in my MVC4 application.

This is the class:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class isAuthorized : AuthorizeAttribute { public oRoles enRole; protected override bool AuthorizeCore(HttpContextBase httpContext) { var authorized = base.AuthorizeCore(httpContext); string test = enRole.ToString(); if (!authorized) { // The user is not authenticated return false; } var user = httpContext.User; bool bFlag = AuthCheck.CheckUser(httpContext, enRole); if (bFlag) // I know this is a lot of code; it for debugging purposes return true; return false; } } 

I have the following listing declared to resolve code:

 public enum oRoles { StudentSelfPassword = 1, StaffSelfPassword = 2, StudentLookup = 3, StudentChangeRequest = 4, StudentAdmin = 5, StaffLookup = 6, StaffChangeRequest = 7, StaffAdmin = 8, ChangeQueueApproval = 9 } 

In my controller, I call AuthorizeAttribute:

  [isAuthorized(enRole = oRoles.StudentLookup)] [isAuthorized(enRole = oRoles.StaffLookup)] [isAuthorized(enRole = oRoles.StudentChangeRequest)] [isAuthorized(enRole = oRoles.StaffChangeRequest)] 

When I run it through the debugger, the first one starts autostart and returns true (as it should), and the second goes to assembler, where it returns false, and then immediately asks me for authentication. I expected this to allow, because the first condition was true. However, it seems my assumption was wrong.

Initially, I had Roles = "change, admin", which were groups in the domain, and it worked, but the groups had to be dynamic in their purpose, and not static. There I was able to click a few elements. Is it because it is sent as a string?

Is there a way to essentially do anAuthorized (...) || isAuthorized (...) || isAuthorized (...), so if one condition is true, is it checked as ok?

+4
source share
1 answer

In your attribute, instead of having a property with one oRole, you can have a list or an array of roles. And instead of putting multiple attributes, decorate your method with a single attribute, but pass it an array of allowed roles.

 [isAuthorized(enRoles = new oRoles[]{oRoles.StudentLookup, oRoles.StaffLookup })] 

An example of creating an attribute that takes multiple values ​​is here.

Then, in your authorization verification code, you can check all the allowed lists that have been provided. Something like the code below

  bool bFlag = enRoles.ToList().Any( r => AuthCheck.CheckUser(httpContext, r)); 
+8
source

All Articles